High-performance Web development: Reflow and redraw

Source: Internet
Author: User

Dom programming can be the most time-consuming place to rearrange and redraw.

1. What is reflow and redraw
After the browser has downloaded all the components in the page--html tags, JavaScript, CSS, and images will parse the resulting 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 rendered tree (the hidden DOM element has a disply value of none in the render trees without corresponding nodes). The nodes in the render tree are called "frames" or "boxes" that conform to the definition of the CSS model and understand the page elements as a box with padding, margins, borders, and positions. Once the DOM and render tree are built, the browser begins to display (draw) the page elements.

When DOM changes affect the geometry of the element (wide or high), the browser needs to recalculate the geometry of the element, and the geometry properties and position of the other elements are affected as well. The browser invalidates the affected portions of the render tree and reconstructs the render tree. This process is 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. With the exception of table and its internal elements, it may take several calculations to determine the properties of its nodes in the render tree, which typically takes 3 times times the same time as the elements. 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. How much does it cost to rearrange and redraw?
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" one hand caused, each "bridge" is actually accompanied by the emphasis row and redraw, and the vast majority of energy consumption is here!

varTimes =15000;//Code1 every bridge + reflow + Redraw access + Modify for(vari =0; I < times; i++) {document.getElementById ('MyDiv1'). InnerHTML + ='a';}
//Code2 only to cross the bridge only to accessvarstr ="'; for(vari =0; I < times; i++) { varTMP = document.getElementById ('MyDiv2'). InnerHTML; STR+='a';} document.getElementById ('MyDiv2'). InnerHTML = str;//Modify Here//Code3var_str ="'; for(vari =0; I < times; i++) {_str+='a';} document.getElementById ('MyDiv3'). InnerHTML = _str;//here once access + modify//1:2874.619ms//2:11.154ms//3:1.282ms

Data is not a lie, see, multiple access to the DOM for Reflow and redraw, the time is simply insignificant.

3. When the rearrangement occurs
Obviously, each rearrangement will inevitably lead to repainting, so in what cases will reflow occur?

1. Add or remove visible DOM elements
2. Change of element position
3. Element size Change
4, the element content changes (for example: one text is replaced by another picture of different sizes)
5. Page rendering initialization (this cannot be avoided)
6. browser window size Change
These are obvious, perhaps you have had this experience, constantly changing the size of the browser window, causing the UI unresponsive (some of the lower version ie even directly hanging off), now you may suddenly realize, yes, it is again and again the reflow redraw caused!

4. Queue and refresh of render tree changes
Consider the following code:

var ele = document.getElementById ('mydiv'1px'  ' 2px ' 5px '; 

At first thought, the style of the element changed three times, each change will cause a rearrangement and redraw, so there are a total of three reflow redraw process, but the browser is not so stupid, it will make three changes to "save" (most browsers through the queue modification and batch execution to optimize the rearrangement process), once completed! However, there are times when you may (often unknowingly) force the queue to flush and ask the scheduled task to execute immediately. Getting the layout information can cause the queue to refresh, 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  "  Span style= "color: #000000"); Ele.style.borderLeft  =  " 1px  "  ;ele.style.borderright  =  " 2px   '  

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 value (even if the style attributes changed in the queue have nothing to do with the property values you want to get), so the above code, The first two operations are cached in the render queue for processing, but once the Offsetheight property is requested, the queue executes immediately, so there are two reflow and redraw. So try not to make queries when layout information changes.

5. Minimize Reflow and redraw
We still look at the code above, three style attributes are changed, each affects the geometry of the element, although most modern browsers are optimized to cause only one reflow, but as above, if a timely property is requested, the queue is forced to flush, and this code accesses the Dom four times, An obvious optimization strategy is to synthesize their operations once, so that only the DOM is modified once:

Three different ways:

varEle = document.getElementById ('mydiv');//1. Overriding styleEle.style.cssText ='border-left:1px; border-right:2px; padding:5px ;';//2. Add StyleEle.style.cssText + ='border-left:1px;'//3. Use classEle.classname ='Active';

6. 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 were adding two options to peach and watermelon in your code?

varLis = document.getElementById ('Fruit');varLi = document.createelement ('Li'); li.innerhtml='Apple'; Lis.appendchild (LI);varLi = document.createelement ('Li'); li.innerhtml='Watermelon'; Lis.appendchild (LI);

It's easy to think of the code, but apparently, it's been re-queued two times, how is it broken? As we said earlier, hidden elements are not in the render tree, great, we can first hide the UL element ID fruit (display=none), and then add the Li element, and finally display, but the actual operation may appear flashing, the reason this is easy to understand. At this point, the fragment element is available.

var fragment = Document.createdocumentfragment ();varLi = document.createelement ('Li'); li.innerhtml='Apple'; Fragment.appendchild (LI);varLi = document.createelement ('Li'); li.innerhtml='Watermelon'; Fragment.appendchild (LI);d Ocument.getelementbyid ('Fruit'). AppendChild (fragment);

  The document fragment is a lightweight paper object designed to accomplish such tasks-updating and moving nodes . A handy syntactic 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 reflow is triggered, and only one real-time DOM is accessed.

7. Let elements out of the animation stream
It is a common mode of interaction to show and hide parts of a page in an expanded/collapsed manner. It usually includes a geometric animation of the expanded area, and pushes the rest of the page downward.

In general, rearrangement affects only a small part of the rendering tree, but it can also affect a large portion, even the entire rendering tree. The fewer times a browser needs to rearrange, the quicker the application responds. So when an animation at the top of the page goes through the rest of the page, it causes a costly, large-scale rearrangement that makes the user feel the page a meal. The more nodes you need to recalculate in the render tree, the worse the situation will be.

Use the following steps to avoid most of the reflow in the page:

Use an absolute position to position the animated element on the page, leaving it out of the flow of the document and moving the element up. When it expands, some pages are temporarily overwritten. But this is just a redraw process for a small area of the page, which does not result in reflow and redrawing of most of the page. Resumes positioning at the end of the animation so that only the other elements of the document are moved down one time.

8. Summary

Rearrangement and redrawing are one of the main causes of energy consumption in DOM programming, which can be referred to in the following points when it comes to DOM programming:

(1) Try not to make queries when layout information changes (will cause the render queue to be forced to refresh)
(2) Multiple property changes in the same DOM can be written together (reducing DOM access while lowering the risk of forcing the rendering queue to refresh by 0)
(3) If you want to add the DOM in bulk, you can leave the element out of the document flow, and then bring it into the document stream, which will only trigger a reflow (application of the fragment element)
(4) The element that needs to be re-arranged multiple times, the Position property is set to absolute or fixed so that the element is out of the document flow, and its changes do not affect other elements. For example, an animated element is best set to absolute positioning.

the above is the high-performance JavaScript reflow and repainting of all the introduction, you can combine the first 2 articles: High-performance Web development: DOM Programming and the High-performance Web development: In-depth understanding of page rendering, redrawing, reflow study together, hope that these three articles can help everyone, to solve the doubts of everyone.

High-performance Web development: 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.