JS Optimization in DOM operation

Source: Internet
Author: User

It is very lossy to operate on the DOM frequently, but in the rich Web application we have to write the script inevitably to deal with the DOM, in the end how to optimize the performance bottleneck, roughly from the following three scenarios to consider:

Accessing and modifying DOM elements

Modifying the DOM style will cause the page to redraw and re-typeset

Responding to users with DOM event handlers

Accessing and modifying DOM elements

In the browser, the implementation of the DOM and the implementation of JavaScript are usually kept separate from each other. Here's a look at the main browser's rendering engine and JS engine:

Browser rendering Engine (kernel) JS engine
Ie Mshtml.dll (Trident) Jscript
Chrome WebCore (WebKit) V8
FireFox Gecko Spider-monkey/tracemonkey
Safari WebCore (WebKit) Javascriptcore/squirrelfish

The cost of accessing the DOM element is to pay a "bridge fee", and modifying the DOM element will cause the browser to recalculate the page's geometric changes. The cost of modifying DOM elements is predictable. The following code:

function InnerHTMLLoop1 () {
  for (Var count=0;count<10000;count++) {
  document.getElementById ("Test"). InnerHTML + = "Add content";
  }
}

In this code, the DOM element is accessed two times per loop at a time: one is to read the contents of the innerHTML property, and the other is to write the new content to it. So an optimization method is to use a local variable to store the updated content, at the end of the loop to write once more:

function InnerHTMLLoop2 () {
var content = "";
  for (Var count=0;count<10000;count++) {
  Content + = "additions";
  }
  document.getElementById ("Test"). InnerHTML + = content;
}
Obviously, INNERHTMLLOOP2 's "bridge fee" is significantly less because it accesses only two DOM elements, one read, one write.

Two method performance comparisons for updating pages: innerHTML and Dom methods (such as Document.createlment). Performance difference is not small, innerhtml better, use simple. Another way to update the page is to clone the node--element.clonenode ().

Operation of the HTML collection

An HTML collection is a class array object used to hold a DOM node reference. You can get such a collection by using the following methods or properties:

Document.getelementsbyname ()
document.getElementsByTagName ()
Document.getelementsbyclassname ()
Document.images returns a reference to all the Image objects in the document
Document.links returns references to all area and Link objects in the document
Document.forms returns a reference to all Form objects in the document
Document.forms[0].elements returns all elements of the first form in a document

The HTML collection queries the document information in real time , which means that when you use the collection, it automatically queries the document for the latest information. Take a look at the following code:

var alldivs = document.getelementsbytagname ("div");  
for (Var i=0;i<alldivs.length;i++) {
       Document.body.appendChild (document.createelement ("div"));  
}

For example, the code above is actually a dead loop, because every time you access the Length property of a Div collection, it recalculates the number of DIV elements in the document. This is the source of inefficient HTML collections. To improve the code, save the length property of the Div collection with a local variable:

For (var i=0, len=alldivs.length; i<len; i++) {...}


The length of the access HTML collection is slower than the length of the array, so to access the number of this collection class length, we should first use a local variable to save it:

var len = set. Length;

In addition, accessing the elements of an array is faster than accessing the elements of an HTML collection. So we can first convert the HTML collection to an array to do the corresponding operation: 
HTML Collection Conversion Array
function ToArray (coll) {
  for (Var a=[], i=0, len=coll.legnth; i<len; i++) {
  A[i] = Coll[i];
  }
  return A;
  }
Use
var coll = document.getelementsbytagname ("div");
var divs = ToArray (coll);
One might ask, is it worth the extra use of an array copy? It depends on the situation. Another option, however, is to use a local variable:
function Loopcolletion () {
  var coll = document.getelmentsbytagname ("div");
  var len = coll.length;
  var el = null;
  for (var i = 0; i<len; i++) {
  El = Coll[i];
  Then access the local variable El
  }
  }
Many browsers provide API functions that return element nodes, which are native, so use as much as you can. Lists some of the DOM's properties:

All of the listed properties are supported by Ff,safari,chrome,opera, ie6-8 only support children.

Traversing children is faster than childnodes because there are fewer collection items. The spaces in the HTML source are actually text nodes, but they are not included in the children.

There are also two better selectors API:document.querySelectorAll () and Document.queryselector (). The former receives a CSS selector string parameter and returns a NodeList class array object instead of returning an HTML collection, which returns only the first node that meets the query criteria. Unfortunately IE6, 7 does not support these two APIs.

JS optimization in DOM operation

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.