The browser renders the page procedure description, Dom programming tips, and reflow and redraw.

Source: Internet
Author: User

One, browser rendering page procedure description

1, browser parsing HTML source code, and then create a DOM tree.

In the DOM tree, each HTML tag has a corresponding node (the element node), and each text has a corresponding node (the text node).

The root node of the DOM tree is documentelement, which corresponds to the HTML tag.

2, the browser parses the CSS code, calculates the final style data.

It is ignored for illegal syntax in CSS code.

When parsing CSS, the precedence is defined in the following order: Browser defaults, user settings, inline styles, inline styles, style in HTML ( Inter - row styles embedded in tags ).

3. After creating the DOM tree and getting the final styling data, build a rendering tree.

The render tree and the DOM tree are a bit like, but there are differences. The DOM tree corresponds exactly to the HTML tag one by one, and the render tree ignores elements that do not need to be rendered (head, display:none elements).

Each node in the render tree stores the corresponding CSS properties.

4. When the render tree is created, the browser can draw the page directly to the screen based on the render tree.

Second, high-performance JavaScript DOM programming

We know that the cost of scripting DOM operations is expensive. The DOM and the ECMAScript each imagined as an island, between them with a toll bridge link, ECMAScript each access to the DOM, will pass through the bridge, and pay "bridge fee", access to the DOM more times, the higher the cost. Therefore, the recommended practice is to minimize the number of crossings, and strive to stay on ECMAScript Island. This is a metaphor for the very image. So how can it be efficient?

1. Dom Access and modification

There is a cost to accessing the DOM element (in fact, it is the same as the AJAX background data interface, where the DOM is an application interface for manipulating XML and HTML documents, not multiple requests at a time), and the cost of modifying elements is more expensive after fetching the elements through the DOM. Because it causes the browser to recalculate the geometric changes (reflow and redraw) of the page.

Example:

var times = 15000;

Code1

Console.time (' time1 ');

for (var i=0; i<times; i++) {

document.getElementById (' MyDiv1 '). InnerHTML + = ' a ';

}

Console.timeend (' time1 ');

Code2

Console.time (' time2 ');

var str = ';

for (var i=0; i<times; i++) {

str + = ' a ';

}

document.getElementById (' MaDiv2 '). InnerHTML = str;

Console.timeend (' time2 ');

Result Time1:2352.064ms/time2:0.789ms

The problem with the first code is that each iteration of the loop will be accessed two times: Read the value of innerHTML one time and rewrite it another time.

As a result, the more times the DOM is accessed, the slower the code runs.

As a result, you can reduce the number of DOM accesses as much as possible and stay on the ECMAScript side of the process.

2. HTML Collection & Traversal DOM

Another energy point for manipulating the DOM is to traverse the DOM, and when it gets a set of elements (the getElementsByTagName method), the result is a class array object, which is in real-time presence in a "real-time state," which means it is automatically updated when the underlying document object is updated.

Example:

And this is the source of inefficiency! Quite simply, as with array optimizations, caching a length variable is ok (reading the length of a collection is much slower than reading the length of an ordinary array, because it is queried every time):

Console.time (' TIME0 ');

var lis0 = document.getelementsbytagname (' li ');

var str0 = ';

for (var i=0; i<lis0.length; i++) {

STR0 +=lis0[i].innerhtml;

}

Console.timeend (' TIME0 ');

Console.time (' time1 ');

var lis1 = document.getelementsbytagname (' li ');

var str1 = ';

for (var i=0; len=lis1.length; i<len; i++) {

STR1 + = lis1[i].innerhtml;

}

Console.timeend (' time1 ');

Results: Time0:0.237ms/time1:0.099ms

The performance gain is noticeable when the object length of this class array is particularly large (for example, 1000).

The first part mainly introduces two optimization, one is to minimize the access of the DOM, put the operation on the ECMAScript end, and the second is to cache local variables, such as the length of the class array object.

Three, rearrange and redraw

1. What is reflow and redraw

After the browser has downloaded all the components in the page (HTML tags, Javascript, CSS, pictures), it resolves to generate two internal data structures--dom tree and render tree.

The DOM tree represents the page structure, and the render tree represents how the DOM nodes are displayed. Each node in the DOM tree that needs to be displayed has at least one corresponding node in the render tree (the hidden DOM element Display:none does not have a corresponding node in the render tree).

The nodes in the render tree are called ' frames ' or ' boxes ' that conform to the definition of the CSS model, and the page element is a box with padding, margins, borders, and positions. Once the DOM tree and render tree are built, the browser starts drawing the page elements.

When DOM changes affect the geometric properties (width or height) of an element, the browser needs to recalculate the geometry of the element, while the geometry properties and position of the other elements are affected. The browser invalidates the affected portions of the render tree and reconstructs the render tree, a process called reflow. When the reflow is complete, the browser redraws the affected section to the screen, which is called redrawing.

Because of the browser's flow layout, the calculation of the render tree is usually done by traversing only once. Except for table and its internal elements, it may take several calculations to determine the properties of its nodes in the render tree, which typically takes three times times the same element. This is one reason why we should avoid using table for layout.

Not all DOM changes affect geometric properties, such as changing the background color of an element without affecting the width and height of the element, in which case only repainting occurs.

2. When the rearrangement occurs

A, add or remove visible DOM elements

b, Element position change

C, Element size change

D. Changes in element content

E, page rendering initialization

F, browser window size change

3. Queue and refresh of render tree changes

Getting the layout information can cause the queue to refresh, such as the following:

A, Offsettop,offsetleft,offsetwidth,offsetheight

B, Scrolltop,scrollleft,scrollwidth,scrollheight

C, Clienttop,clientleft,clientwidth,clientheight

D, Getcomputestyle () | | Currentstyle (IE)

Because the Offsetheight property needs to return the most recent layout information, the browser has to perform "pending changes" in the render queue and trigger the reflow to return the correct values (even if the style attributes changed in the queue are not related to the property values you want to get).

4. Minimize reflow and redraw

When changing the elements of multiple styles, it is best to use classname, one time to complete the operation, which will only modify the DOM.

5. Document Fragmentation

Document fragmentation is designed to accomplish such tasks-updating and moving nodes. When you attach a fragment to a node, it is actually added to the child node of the fragment, not the fragment itself. Only one reflow is triggered, and only one real-time DOM is accessed.

Usage:

var ofragment = document.createdocumentfragment ();

for (var i=0; i<1000; i++) {

var OP = document.createelement (' P ');

op.innerhtml = i;

Ofragment.appendchild (OP);

}

var oDo = document.body;

Odo.appendchild (ofragment);

6. Let the animation out of the document flow

Use an absolute position to position the animated element on the page, leaving it out of the document flow. This does not cause elements in the document flow to be affected, and does not reflow and redraw on a large scale.

The second part rearrangement and redrawing is one of the main causes of energy consumption in DOM programming, so you can refer to the following points to avoid unnecessary performance losses:

1, try not to make the layout information changes when the query (will cause the rendering queue forced to refresh);

2. Multiple attribute changes of the same DOM can be written together (reduce DOM access while reducing the risk of forced-render queue refreshes to 0);

3, if you want to bulk add the DOM, you can first leave the element out of the document flow, the operation is completed with the human document flow, which will only trigger a reflow (fragment element of the application);

4, will need to rearrange the elements, add positioning attributes, set to absolute,fixed, so that this element is out of the document flow, not affect other elements.

The browser renders the page procedure description, Dom programming tips, and reflow and redraw.

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.