High-performance JavaScript (2) DOM programming

Source: Internet
Author: User
Tags tagname

Part Three DOM programming

The Document Object Model (DOM) is a language-independent application interface (API) that uses XML and HTML document operations. In a browser, it is also common to work with HTML documents primarily, and to retrieve XML documents in Web applications. DOM APIs are primarily used to access data in these documents. Although the DOM is a language-agnostic API, the interface in the browser is implemented in JavaScript. The majority of the client's scripts interact with the document, and the DOM becomes an important part of the daily behavior of JavaScript code.

2.1 Dom Access and modification DOM accesses and modifies

Simply put, as discussed earlier, the cost of accessing a DOM element is to pay a "bridge fee". The cost of modifying an element can be more expensive because it often causes the browser to recalculate the geometry of the page. As in the following example:

function Innerhtmlloop () {for  (var count = 0, count < 15000; count++) {  document.getElementById (' here '). Inner HTML + = ' a ';  } }

This function updates the page content in a loop. The problem with this code is that the DOM element is accessed two times in each loop unit: Once read the innerHTML property can tolerate and write to it another time. Therefore, the quickest way is to generate a complete string and then modify and access the DOM element once and for all.

function InnerHTMLLoop2 () {  var content = ';  for (var count = 0; count < 15000; count++) {  content + = ' a ';  }  document.getElementById (' here '). InnerHTML + = content; }

These results make it clear that the more DOM you access, the slower your code will execute. Therefore, the general rule of thumb is to touch the DOM gently and try to keep it within the ECMAScript range.

2.2 InnerHTML Versus DOM methods InnerHTML compared to DOM methods

Over the years, there has been a lot of discussion on this issue in the Web Developer community: Is it better to update pages with innerHTML attributes that are not standard but well supported, or to use a pure DOM approach, document.createelement ()? If you don't consider standard issues, how do they perform? The answer is: performance is not very different, but in all browsers, innerHTML is faster, in addition to the latest WebKit-based browsers.

function tableinnerhtml () {var i, h = [' <table border= ' 1 ' width= ' 100% ' > '];  H.push (' <thead> '); H.push (' <tr><th>id<\/th><th>yes?<\/th><th>name<\/th><th>url  <\/th><th>action<\/th><\/tr> ');  H.push (' <\/thead> ');  H.push (' <tbody> ');  for (i = 1; i <=; i++) {H.push (' <tr><td> ');  H.push (i);  H.push (' <\/td><td> '); H.push (' And the answer is ... ' + (i% 2?)  ' Yes ': ' no ');  H.push (' <\/td><td> ');  H.push (' My name is # ' + i);  H.push (' <\/td><td> ');  H.push (' <a href= ' http://example.org/' + i + '. html ">http://example.org/' + i + ' .html<\/a> ');  H.push (' <\/td><td> ');  H.push (' <ul> ');  H.push (' <li><a href= ' edit.php?id= ' + i + ' ">edit<\/a><\/li> ');  H.push (' <li><a href= ' delete.php?id= ' + i + '-id001 ' >delete<\/a><\/li> ');  H.push (' <\/ul> '); H.push (' <\/td> '));  H.push (' <\/tr> ');  } h.push (' <\/tbody> ');  H.push (' <\/table> '); document.getElementById (' here '). InnerHTML = H.join ("); };

The example above describes the way in which elements are generated using innerHTML. We're just going to remember these basic ways here.

2.3 Cloning Nodes node cloning

2.4 HTML Collections HTML Collection

An HTML collection is a class array object used to hold a DOM node reference. The return value of the following function is a collection:
Document.getelementsbyname ()
Document.getelementsbyclassname ()
Document.getelementsbytagname_r ()

The following properties are also part of the HTML collection:

    • Document.images all elements in the page
    • Document.links all the <a> elements

    • Document.forms All Forms

    • Document.forms[0].elements all fields of the first form in a page

These methods and properties return the Htmlcollection object, which is a list of similar arrays. They are not arrays (because they do not have methods such as push () or slice (), but they provide a length property that, as well as arrays, you can use to access the elements in the list.

2.4 Expensive collections expensive collection

As will be discussed in the fourth chapter, it is not recommended to use the length property of the array for cyclic judging conditions. The length of the access collection is slower than the length of the array, because it means that the query process is rerun every time.

In the following example, the three properties of each element are accessed in a loop. The slowest version accesses the global document every time, and the optimized version caches a reference to the collection, and the fastest version stores the current element of the collection in a local variable. All three versions cache the length property of the collection.

Slow function Collectionglobal () {  var coll = document.getelementsbytagname_r (' div '),  len = coll.length,  name = ';  for (var count = 0; count < Len; count++) {  name = Document.getelementsbytagname_r (' div ') [Count].nodename;  Name = Document.getelementsbytagname_r (' div ') [Count].nodetype;  Name = Document.getelementsbytagname_r (' div ') [Count].tagname;  }  return name; };

Faster function collectionlocal () {  var coll = document.getelementsbytagname_r (' div '),  len = coll.length,< C11/>name = ";  for (var count = 0; count < Len; count++) {  name = Coll[count].nodename;  name = Coll[count].nodetype;  name = Coll[count].tagname;  }  
Fastest function collectionnodeslocal () {  var coll = document.getelementsbytagname_r (' div '),  len = Coll.length,  name = ' ',  el = null;  for (var count = 0; count < Len; count++) {  el = coll[count];  name = El.nodename;  name = El.nodetype;  name = El.tagname;  }  return name; };

There are a number of areas where DOM operations can be high performance, such as accessing sibling nodes and child nodes, and so on.

2.5 The Selectors API Selector API

When identifying elements in the DOM, developers often need finer control than functions such as getElementById () and Getelementsbytagname_r (). Sometimes you combine these functions to invoke and iterate over the nodes they return to get the elements you need, and this fine process can be inefficient. On the other hand, using CSS selectors is a convenient way to determine nodes, because developers are already familiar with CSS. Many
The JavaScript library provides an API for this, and the latest browser provides a native browser Dom function named Queryselectorall (). Obviously this approach is faster than using JavaScript and Dom to iterate and narrow the list of elements. As shown below:

var elements = Document.queryselectorall (' #menu a ');

The value of elements will contain a list of references to the elements that have the id= "menu" property. The function Queryselectorall () receives a CSS selector string parameter and returns a nodelist--class array object that is composed of eligible nodes. This function does not return an HTML collection, so the returned node does not render the document's "existence structure". This avoids the performance issues inherent in the HTML collections mentioned earlier in this chapter (and potential logical problems).

If you do not use Queryselectorall (), the code that achieves the same goal will be verbose:
var elements = document.getElementById (' menu '). Getelementsbytagname_r (' a ');

In this case elements will be an HTML collection, so you'll also need to copy it into an array if you want to
Queryselectorall () The same return value type.

Summary

Dom access and manipulation is an important part of modern web applications. But every time you reach Dom Island through a bridge from ECMAScript Island
, you will be charged a "bridge fee". To reduce the performance penalty in DOM programming, keep in mind the following points:


Minimize DOM access, and try to work as much as possible in JavaScript.
Minimize DOM access and do as many things as possible on the JavaScript side.
use local variables to store DOM references for you access repeatedly.
Use local variables to hold DOM references where you repeatedly visit.
be careful when dealing with Htmlcollections because theyrepresent the live, underlying document. Cache
The collection lengthinto a variable and use it if iterating, and make a copy of the collection to an array for
Heavy work on collections.
Handle HTML collections with care because they exhibit "presence" and always requery the underlying document. The length property of the collection is deferred
In a variable, use this variable in the iteration. If you work with this collection frequently, you can copy the collection into an array.
use faster APIs when available, such as Queryselectorall () and Firstelementchild.
use faster APIs, such as Queryselectorall () and Firstelementchild, if possible.
be mindful of repaints and reflows; Batch style changes, manipulate the DOM tree "offline," and "cache and
Minimize access to layout information.
Pay attention to redraw and re-typesetting, batch modify style, operate DOM tree offline, cache and reduce access to layout information.
position absolutely during animations, and use drag and drop proxies.

Use absolute coordinates in animations, using drag-and-drop proxies.
Use event Delegation to minimize the number of event handlers.
Minimizing the number of event handles using event-managed technology

High-performance JavaScript (2) DOM programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.