How to reduce browser repaint and reflow

Source: Internet
Author: User
Tags dynatrace
1. What is repaint/reflow?

During the page loading process, the document structure needs to be parsed, and various styles need to be combined to calculate the page length, and then render the page through the browser. This entire
The process is still complex in detail, which is full of repaint and reflow. Each element in the DOM structure has its own box (model ).
(Defined by the browser or developer) to calculate and place the element to its position based on the calculation result. This process is called reflow; when the location, size, and other properties of various boxes, such
After the color and font size are determined, the browser then draws these elements according to their respective characteristics, so the page content appears. This process is called repaint.

The above mentioned only the repaint and reflow that will inevitably occur during page loading. In addition, after page loading is complete, some operations and script operations of the user will lead to browsing.
This behavior is described in the following section.

In addition, for more detailed information about browser rendering, refer to the following, covering IE and Firefox:

Understanding Internet Explorer rendering behaviour

Notes on HTML reflow

Ii. Under what circumstances will the browser's repaint/reflow be triggered?

In addition to the process that must be performed when a page is loaded for the first time, the following actions will trigger this action:

  • Dom element addition, modification (content), deletion (reflow + repaint)
  • Only modify the font color of the DOM element (only repaint is required because the layout does not need to be adjusted)
  • Apply new styles or modify any attributes that affect the appearance of elements.
  • Resize browser window and scroll page
  • Read certain attributes of an element (offsetleft, offsettop, offsetheight, offsetwidth,
    Scrolltop/left/width/height, clienttop/left/width/height,
    Getcomputedstyle (), currentstyle (in IE ))

Before proceeding to the following article, we will introduce dynatrace, a powerful performance analysis tool.
With this function, you can clearly obtain the resource consumption information on the page, so as to remedy the problem. In addition, the more detailed aspect is that it can
To track the CPU consumption and repaint/reflow caused by each function call. Next we will use this tool to test the situations described above.

Addition, deletion, and modification of DOM elements

First look at the code

HTML:

1st nodes
2nd nodes
3rd nodes

Javascript:

        function $(id){
return document.getElementById(id);
}
function addNode(){
var n = document.createElement('div');
n.innerHTML = 'New Node';
$('test1').appendChild(n);
}
function modNode(){
$('test2').innerHTML = 'hello';
}
function delNode(){
$('test3').parentNode.removeChild($('test3'));
}

After clicking each button in turn, let's take a look at the situation of dynatrace. First, click event distribution at a glance.

Zoom in to view the repaint/reflow of each event:

Add nodes:

Modify a node:

Delete a node:

The green part in the figure indicates the reflow and repaint processes. The short green bar indicates the Reflow Process, and the subsequent part indicates the repaint process. Slave
As shown in the figure, adding, deleting, and modifying a DOM node will result in reflow and repaint. Because of the small changes, reflow consumes a short time, but because repaint is global
Therefore, the time consumed is relatively long.

Modify the foreground color of a DOM Element
var n = $('colorNode');
n.style.color = 'red';

 

 

We can see that after the font color is modified, the browser only has repaint without reflow. Next, try to modify the background color:

var n = $('colorNode');
n.style.backgroundColor = 'red';
 

As shown in the figure, modifying the background color also causes reflow and repaint. In addition, tests show that, as long as the csstext attribute of an element is modified, no matter what its value is,
Will cause the browser reflow and repaint, so sometimes selecting a specific style attribute assignment will have a better effect.

Resize the browser window and drag the scroll bar

 

In the test, narrow down the browser window, zoom in the browser window, and drag the page scroll bar to the bottom of the page. You can see the resize browser window and drag and roll
Animation will cause the browser to repaint, And the CPU consumption is also relatively large, especially when dragging the scroll bar.

Read layout attributes

Read the layout attribute (offsetleft, offsettop,
Offsetheight, offsetwidth, scrolltop/left/width/height, clienttop/left
/Width/height, getcomputedstyle (), currentstyle (in IE ))
But this is not found in the following test examples.

var n = $('colorNode');
var temp = document.documentElement.currentStyle;
temp = n.offsetTop;
temp = n.offsetLeft;
temp = n.offsetWidth;
temp = n.offsetHeight;
temp = n.scrollTop;
temp = n.scrollHeight;
alert(temp);

 

3. browser Optimization

The browser does not execute every rendering action immediately, but maintains a rendering task queue. the browser will perform the tasks in batches according to the specific needs. In addition to the regular maintenance of browsers
In addition to scheduling, some operations in the script will cause the browser to immediately execute rendering tasks, such as reading the layout attribute of the element.

VaR bodystyle = Document. Body. style;
VaR computed;
If (document. Body. currentstyle ){
Computed = Document. Body. currentstyle;
} Else {
Computed = Document. defaultview. getcomputedstyle (document. Body ,'');
}

// Read every time

Bodystyle. Color = 'red ';
Bodystyle. Padding = '1px ';
TMP = computed. backgroundcolor;
Bodystyle. Color = 'white ';
Bodystyle. Padding = '2px ';
TMP = computed. backgroundimage;
Bodystyle. Color = 'green ';
Bodystyle. Padding = '3px ';
TMP = computed. backgroundattachment;

// Finally read

Bodystyle. Color = 'yellow ';
Bodystyle. Padding = '4px ';
Bodystyle. Color = 'pink ';
Bodystyle. Padding = '5px ';
Bodystyle. Color = 'Blue ';
Bodystyle. Padding = '6px ';
TMP = computed. backgroundcolor;
TMP = computed. backgroundimage;
TMP = computed. backgroundattachment;

The rendering image read each time:

The last read rendering image:

4. How to optimize your scripts to reduce reflow/repaint?

1.
To avoid frequent Dom operations on documents, you can use the off-document method if necessary. The specific methods include but do not fully include the following:

(1) first Delete the element from the document, and then put the element back to its original position after modification.

(2) set the display of the element to "NONE". After the modification, change the display to the original value.

(3) If you need to create multiple DOM nodes, you can use documentfragment to add the document

Function appendeverytime (){
For (VAR I = 5000; I --;){
VaR n = Document. createelement ('div ');
N. innerhtml = 'node' + I;
Document. Body. appendchild (n);/* the newly created node is appended to the document */
}
}

Function appendlast (){
VaR frag = Document. createdocumentfragment ();
For (VAR I = 5000; I --;){
VaR n = Document. createelement ('div ');
N. innerhtml = 'node' + I;
Frag. appendchild (n);/* Each created node is first placed in documentfragment */
}
Document. Body. appendchild (frag );
}

The results observed with dynatrace are as follows. appendlast has better performance in Javascript execution time and browser rendering time.
Appendeverytime.

Appendeverytime:

Appendlast:

2. Modify styles in a centralized manner

(1). Modify as few attributes as possible on the element style.

(2) try to modify the style by modifying the classname

(3). Set the style value through the csstext attribute

In the following code, each value assignment will cause the browser to re-render. You can use csstext or classname.

el.style.color = 'red;
el.style.height = '100px';
el.style.fontSize = '12px';
el.style.backgroundColor = 'white';

3. cache layout attribute values

For non-reference type values (numeric type) in the layout attribute, if multiple accesses are required, local variables can be stored in the local variables for one access, and then local variables can be used to avoid each access.
Rendering of the browser when reading properties.

var width = el.offsetWidth;
var scrollLeft = el.scrollLeft;

4. Set the position of the element to absolute or fixed.

When the position of an element is static or relative, the element is in the DOM tree structure. When an operation on the element needs to be re-rendered, the browser renders the entire page.
. Setting the position of an element to absolute and fixed can separate the element from the DOM tree structure. The browser only needs to render the element when rendering.
And the elements located below the element to shorten the browser rendering time to some extent, which is particularly worth considering in today's more and more JavaScript animations.

HTML code:

Animation Here

JavaScript code:

var t = $('test');
~function(){
t.style.left = t.offsetLeft + 5 + 'px';
t.style.height = t.offsetHeight + 5 + 'px';
setTimeout(arguments.callee,500);
}();

Modify the postion of the # test element as relative and postion to obtain the following two test results:

Position: relative

Position: absolute

 

In the postion: relative test, the browser does more work than position: absolute when re-rendering.
A lot.

Reprinted http://blog.csdn.net/baiduforum/archive/2010/03/25/5415527.aspx http://blog.csdn.net/baiduforum/archive/2010/03/25/5416337.aspx http://blog.csdn.net/baiduforum/archive/2010/03/25/5416352.aspx

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.