Dom performance bottlenecks and JavaScript performance optimizations

Source: Internet
Author: User

These two days more busy, wrote two of JS performance defects and solutions of the article ("JS performance defects and JIT solution," "JavaScript garbage Collection Analysis"), mainly describes the problem of UNTYPED,GC and JIT engine solutions. But with respect to the JS engine, I think the DOM-led performance problem deserves more attention.

I. Performance bottlenecks and causes of DOM

1. Why is DOM

The standard xml/html Text parsing protocol, common to have DOM and sax. Sax has an advantage over DOM in parsing speed and memory footprint, but why does the browser choose DOM parsing HTML?

(1) DOM VS SAX

Sax provides a one-time parsing of text, does not generate objects, iterator mode access elements, Event-based,push mode trigger, simply said: The app needs to register with parser, when parser traverse the XML, trigger call app. To experience it, use the javax.xml.parsers.SAXParser. Here is a digression, the improved version of Stax is the pull mode, but this is not important, it is important: one-time text parsing, do not generate objects.

After the DOM parses the text, it generates a DOM tree. That is: one-time text parsing, generating objects.

(2) Dom selected by browser

A single efficiency DOM is not as good as sax, but Sax does not generate objects, and many of the browser's operations are difficult to meet, such as: element positioning, element style rendering ... So Dom is the inevitable choice.

2. DOM Performance issues

"1" Core issues

When parsing an HTML file that is large, generating a DOM tree takes up a large amount of memory while traversing (not updating) an element is time-consuming. But this is not the point, Dom's core problem is:dom modification resulting in page redraw, re-layout ! Re-typesetting is a user-blocked operation, and the CPU usage will skyrocket if frequent rearrangement occurs!

DOM operations result in a series of redraw (repaint), re-typesetting (reflow) operations. To ensure the accuracy of the execution results, all modifications are performed sequentially. Most browsers do not update the DOM during JavaScript execution. Accordingly, these browsers put the action on the DOM into a queue and execute it sequentially once the JavaScript script has finished executing. That is, during JavaScript execution, the user is blocked until the re-typesetting occurs.

in general browsers (ie not included), repaint speed is much faster than reflow, so it is more important to avoid reflow .

causes the operation of repaint, Reflow :

* DOM element Additions, modifications (contents), Deletions (Reflow + Repaint)

* Only modify the font color of DOM elements (only repaint, because you do not need to adjust the layout)

* Apply a new style or modify any attributes that affect the appearance of an element

* Resize browser window, scrolling page

* Read some attributes of an element (Offsetleft, OffsetTop, offsetheight, offsetwidth, Scrolltop/left/width/height, clienttop/left/width/ Height, getComputedStyle (), Currentstyle (in IE))

"2" Other

Some JavaScript frameworks, CSS selectors, such as: var el = $ ('. hyddd '); because IE6, 7 is not supported, the JavaScript framework must look for objects by traversing the entire DOM tree.

Two. For DOM problems, JavaScript's solution

1. For repaint, Reflow,nicholas uncle in his "speed Up your JavaScript, Part 4" Did a detailed introduction, here I also tidy up:

the key to solving the problem is to reduce the reflow caused by DOM manipulation. Nicholas summarizes some of the methods:

"1" performs as many change operations as possible outside the DOM. Demo:

Bad practices for (var i=0; i < items.length; i++) {    var item = document.createelement ("li");    Item.appendchild (document.createTextNode ("Option" + i);    List.appendchild (item);}
Better practices//Use containers to store temporary changes, and finally update domvar fragment = Document.createdocumentfragment (); for (var i=0; i < items.length; i++) {    var item = document.createelement ("li");    Item.appendchild (document.createTextNode ("Option" + i);    Fragment.appendchild (item);} List.appendchild (fragment);

"2" before manipulating the DOM, remove or hide the DOM nodes, because hidden nodes do not trigger reflow. The demo is as follows:

List.style.display = "None";  for (var i=0; i < items.length; i++) {      var item = document.createelement ("li");      Item.appendchild (document.createTextNode ("Option" + i);      List.appendchild (item);  }  List.style.display = "";  

"3" Once, modify the style properties. The demo is as follows:

Bad practice//This practice will trigger multiple reflow Element.style.backgroundColor = "Blue";  Element.style.color = "Red";  Element.style.fontSize = "12em";
A better approach is to put the styles under one class. NewStyle {      background-color:blue;      color:red;      font-size:12em;  }  Element.classname = "NewStyle";

"4" uses caching to cache temporary nodes.

Bad practice document.getElementById ("mydiv"). Style.left = document.getElementById ("mydiv"). Offsetleft +  document.getElementById ("Mydiv"). offsetwidth + "px";  
Better practice var mydiv = document.getElementById ("mydiv");  MyDiv.style.left = mydiv.offsetleft + mydiv.offsetwidth + "px";  

2. Pin Select its problem, I can only say: No way ...: (

Three. Reference Resources

1. Top ten root causes of WEB 2.0 application client performance issues

2. "Speed Up your" JavaScript, Part 4

Dom performance bottlenecks and JavaScript performance optimizations

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.