High performance JavaScript rearrangement and redrawing (2) _javascript tips

Source: Internet
Author: User
Tags flush html tags require

First of all, review the next article high-performance JavaScript DOM programming , mainly two point optimization, one is to minimize access to the DOM, while the operation on the ECMAScript side, the second is to cache local variables, such as length and so on, Finally, two new API Queryselector () and Queryselectorall () are introduced, which can be used boldly when making portfolio selection. This article is mainly about the most time-consuming place where DOM programming can be, rearrange and redraw.

1, what is rearrangement and redrawing
After the browser has downloaded all of the components in the page--html tags, JavaScript, CSS, pictures will resolve to generate two internal data structure-dom tree and rendering tree.

The DOM tree represents the page structure, and the rendering 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 rendered tree (the hidden DOM element disply value is none in the render trees). The nodes in the render tree are called "frames" or "boxes", which conform to the definition of the CSS model and understand that the page element is a box with padding, margins, borders, and positions. Once the DOM and the render tree are built, the browser begins to display (draw) the page elements.

When changes in the DOM affect the geometry of the element (width or height), the browser needs to recalculate the geometric attributes of the elements, as well as the geometric properties and position of the other elements. The browser invalidates the affected part of the render tree and reconstructs the render tree. This process is called rearrangement . When the rearrangement is complete, the browser will redraw the affected section to the screen, which is called redraw . Because of the flow layout of the browser, the calculation of the render tree usually takes only one time to complete. Except for a table and its internal elements, it may require multiple computations to determine the properties of its nodes in the render tree, usually 3 times times the same element. This is one reason why we should avoid using table as a layout.

Not all DOM changes affect geometric attributes, such as changing the background color of an element and not affecting the width and height of the element, in which case the redraw will only occur.

2, rearrange and redraw the cost of how much
How much does it cost to rearrange and redraw? We go back to the previous example of the bridge, careful you may find that the time difference is not due to the "bridge" single-handedly caused, each "bridge" in fact, with emphasis on row and redraw, and the vast majority of energy consumption is here!

var times = 15000;

Code1 each bridge + rearrangement +
console.time (1);
for (var i = 0, i < times; i++) {
 document.getElementById (' MyDiv1 '). InnerHTML + = ' a ';
}
Console.timeend (1);

Code2 only Bridge
Console.time (2);
var str = ';
for (var i = 0, i < times; i++) {
 var tmp = document.getElementById (' MyDiv2 '). InnerHTML;
 STR + + ' a ';
}
document.getElementById (' MyDiv2 '). InnerHTML = str;
Console.timeend (2);

Code3 
Console.time (3);
var _str = ';
for (var i = 0; I < times; i++) {
 _str + = ' a ';
}
document.getElementById (' MyDiv3 '). InnerHTML = _str;
Console.timeend (3);


1:2874.619ms
//2:11.154ms
//3:1.282ms

Data is not a lie, see, multiple access to the DOM for rearrangement and redrawing, the time is simply not worth mentioning.

3. When the rearrangement occurs
Obviously, each rearrangement will inevitably result in redrawing, so in what cases will the rearrangement occur?

1. Add or remove visible DOM elements
2, Element position change
3, Element size change
4, the element content changes (for example: one text by another different size picture replaces)
5, page rendering initialization (this can not be avoided)
6, browser window size changes
These are obvious, perhaps you have had this experience, constantly changing the size of the browser window, causing the UI to slow down (some of the lower version of IE even directly hung out), now you may suddenly understand, yes, it is the repeated rearrangement of the cause!

4, rendering tree changes in the queue and refresh
Consider the following code:

var ele = document.getElementById (' mydiv ');
Ele.style.borderLeft = ' 1px ';
Ele.style.borderRight = ' 2px ';
ele.style.padding = ' 5px ';

At first thought, the style of the element changed three times, each change will cause a rearrangement and redraw, so there are three times to rearrange the redraw process, but the browser is not so stupid, it will be three changes to "save" (most of the browser through the queue to modify and batch execution to optimize the rearrangement process), a complete! However, sometimes you might (often unconsciously) force a flush queue and require that the scheduled task be executed immediately. Obtaining layout information can cause queues to be refreshed, such as the following:

1.offsetTop, Offsetleft, offsetwidth, offsetheight
2.scrollTop, ScrollLeft, ScrollWidth, scrollheight
3.clientTop, ClientLeft, ClientWidth, clientheight
4.getComputedStyle () (Currentstyle in IE)
Modify the above code slightly:

var ele = document.getElementById (' mydiv ');
Ele.style.borderLeft = ' 1px ';
Ele.style.borderRight = ' 2px ';

Here, use offsetheight
//...
ele.style.padding = ' 5px ';

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 rearrangement to return the correct value (even if the changed style attribute in the queue has nothing to do with the property value you want to get), so the above code, The first two operations are cached in the render queue, but once the offsetheight attribute is requested, the queue executes immediately, so there are two times to rearrange and redraw. So try not to make inquiries when layout information changes.

5, minimize the rearrangement and redraw
Let's look at the code above:

var ele = document.getElementById (' mydiv ');
Ele.style.borderLeft = ' 1px ';
Ele.style.borderRight = ' 2px ';
ele.style.padding = ' 5px ';

Three style attributes are changed, each will affect the geometry of the elements, although most modern browsers are optimized to cause only one rearrangement, but like the above, if a timely attribute is requested, then the queue is forced to flush, and this code accesses the Dom four times, An obvious optimization strategy is to synthesize their operations once, which only modifies the DOM once:

var ele = document.getElementById (' mydiv ');

1. Rewrite style
ele.style.cssText = ' border-left:1px; border-right:2px; padding:5px; ';

2. Add Style
Ele.style.cssText + = ' border-;eft:1px; '

3. Use class
Ele.classname = ' active ';

6, the application of fragment elements
Look at the following code to consider a problem:

<ul id= ' fruit ' >
 <li> apple </li>
 <li> Orange </li>
</ul>

What would you do if you wanted to add content to peach, watermelon two options in your code?

var lis = document.getElementById (' fruit ');
var li = document.createelement (' li ');
li.innerhtml = ' Apple ';
Lis.appendchild (LI);

var li = document.createelement (' li ');
li.innerhtml = ' watermelon ';
Lis.appendchild (LI);

It's easy to think of code like this, but apparently, two times, how do you break it? We said that the hidden elements are not in the rendering tree, it is great, we can first the ID for the fruit of the UL element to hide (Display=none), and then add Li elements, and finally show, but the actual operation may appear flashing, the reason this is also easy to understand. At this point, the fragment element will have a useful.

var fragment = Document.createdocumentfragment ();

var li = document.createelement (' li ');
li.innerhtml = ' Apple ';
Fragment.appendchild (LI);

var li = document.createelement (' li ');
li.innerhtml = ' watermelon ';
Fragment.appendchild (LI);

document.getElementById (' fruit '). appendchild (fragment);

The document fragment is a lightweight documentation object designed to accomplish such tasks-updating and moving nodes. A handy grammatical feature of a document fragment is that 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 rearrangement was triggered, and only one real-time Dom was accessed.

7, let the elements out of the animation stream
displaying and hiding portions of a page in an expanded/collapsed manner is a common mode of interaction. It usually includes a geometric animation of the expanded area and pushes the rest of the page down.

In general, rearrangement affects only a small portion of the rendering tree, but it can also affect a large part, or even the entire rendering tree. The fewer times the browser needs to rearrange, the faster the application responds. So when a page at the top of an animation goes through the rest of the page, it can result in a costly, massive rearrangement, giving the user a good meal on the page. The more nodes that need to be recalculated in the render tree, the worse it will be.

Use the following steps to avoid most of the rearrangement on the page:

Position an animated element on a page by using an absolute position to detach it from the document stream
Let the elements move. When it expands, part of the page is temporarily overwritten. But this is just a redrawing of a small area of the page and does not produce much of the rearrangement and redrawing of the page.
Restores positioning when the animation ends so that only the other elements of the document are moved down once
Summary
rearrangement and redrawing is one of the main causes of energy consumption in DOM programming, and the following points can be consulted when it comes to DOM programming:

Try not to make a query when layout information changes (causing the render queue to force a refresh)
Multiple property changes to the same DOM can be written together (reduce DOM access while reducing the risk of forced rendering queue refreshes to 0)
If you want to add the DOM in bulk, you can leave the element out of the document stream and then bring it into the document stream after the operation, which triggers only one rearrangement (application of the fragment element)
The element that will require multiple rearrangement, the Position property is set to absolute or fixed, so that the element is detached from the document stream, and its changes do not affect other elements. For example, an animated element is best set to absolute positioning.

This is the full description of high-performance JavaScript rearrangement and redrawing, and you can combine a high-performance JavaScript dom Programming (1) to learn,

I hope these two articles can help us to solve all the doubts in this respect.

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.