Home >Web Front-end >HTML Tutorial >css redraw and reflow_html/css_WEB-ITnose

css redraw and reflow_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:51:531085browse

High-performance WEB development of page rendering, redrawing and reflow (1)

2011-04-25 10:11 BearRui BearRui's Blog Font size: T | T

Before discussing page redraws and reflows. You need to have some understanding of the page rendering process, how the page displays HTML combined with CSS, etc. to the browser. The following flow chart shows the browser's processing flow for page rendering. Different browsers may be slightly different. But basically they are similar.

AD: 2014WOT Global Software Technology Summit Beijing Course Video Release

Before the discussion page is redrawn and reflowed. You need to have some understanding of the page rendering process, how the page displays HTML combined with CSS, etc. to the browser. The following flow chart shows the browser's processing flow for page rendering. Different browsers may be slightly different. But basically they are similar.

1. The browser parses the obtained html code into a Dom tree. Each tag in the HTML is a node in the Dom tree, and the root node is what we commonly use. The document object (tag). The dom tree is the html structure we see using tools such as firebug or IE Developer Toolbar. It contains all html tags, including display:none hidden, and elements dynamically added using JS.

2. The browser parses all styles (mainly including css and browser style settings) into style structures. During the parsing process, styles that the browser cannot recognize will be removed. For example, IE will remove -moz The style at the beginning, and firefox will remove the style at the beginning of _.

3. The dom tree and the style structure are combined to build a render tree. The render tree is somewhat similar to the dom tree, but in fact there is a big difference. The render tree can identify styles. Each render tree in the render tree Each node has its own style, and the render tree does not contain hidden nodes (such as display:none nodes and head nodes). Because these nodes will not be used for rendering and will not affect the rendering, they will not be included. into the render tree. Note that elements hidden by visibility:hidden will still be included in the render tree, because visibility:hidden will affect the layout and occupy space. According to the standards of CSS2, each node in the render tree is called a box (Box dimensions), and all the attributes of the box are: width, height, margin, padding, left, top, border, etc.

4. Once the render tree is constructed, the browser can draw the page based on the render tree.

Reflow and redraw

1. When part (or all) of the render tree needs to be rebuilt due to changes in the size, layout, hiding, etc. of the elements. This is called reflow (actually, I think it's simpler and clearer to call it rearrangement). Every page needs to be reflowed at least once, when the page loads for the first time.

2. When some elements in the render tree need to update attributes, these attributes only affect the appearance and style of the elements, but will not affect the layout, such as background-color. It is called redrawing.

Note: As can be seen from the above, reflow will definitely cause redraw, but redraw will not necessarily cause reflow.

What operations will cause redrawing and reflow

In fact, any operation on the elements in the render tree will cause reflow or redrawing, such as:

1. Add and delete elements (reflow and redraw)

2. Hide elements, display:none (reflow and redraw), visibility: hidden (only redraw, no reflow)

3. Move elements, such as changing top and left (jquery's animate method is that changing top and left does not necessarily affect reflow), or move the element to another parent element. (Redraw and reflow)

4. Operations on style (different attribute operations have different effects)

5. There is also a user operation, such as changing the browser size, Changing the browser's font size, etc. (reflow redraw)

Let's see how the following code affects reflow and redraw:

var s = document.body.style;    s.padding = "2px"; // 回流+重绘  s.border = "1px solid red"; // 再一次 回流+重绘   s.color = "blue"; // 再一次重绘  s.backgroundColor = "#ccc"; // 再一次 重绘   s.fontSize = "14px"; // 再一次 回流+重绘   // 添加node,再一次 回流+重绘  document.body.appendChild(document.createTextNode('abc!'));

Note how much I used above again.

Speaking of which, everyone knows that reflow is more expensive than redrawing. The cost of reflow is related to how many nodes in the render tree need to be rebuilt. Assume that you directly operate the body, such as inserting 1 at the front of the body. Elements will cause the entire render tree to reflow, which will of course be more expensive. However, if an element is inserted after the body, it will not affect the reflow of the previous elements.

Smart browser

From the previous example code, you can see that a few lines of simple JS code caused about 6 reflows and redraws. And we also know that the cost of reflow is not small. If every JS operation has to be reflowed and redrawn, the browser may not be able to bear it. Therefore, many browsers will optimize these operations. The browser will maintain a queue and put all operations that will cause reflow and redrawing into this queue. When the operations in the queue reach a certain number or a certain time interval, the browser The flush queue will be processed in a batch. This will turn multiple reflows and redraws into one reflow and redraw.

Although there are browser optimizations, sometimes some code we write may force the browser to flush the queue in advance, so the browser optimization may not be effective. When you request some style information from the browser, the browser will flush the queue, such as:

1. offsetTop, offsetLeft, offsetWidth, offsetHeight

2. scrollTop/Left/Width/Height

3. clientTop/Left/Width/Height

4. width,height

5. 请求了getComputedStyle(), 或者 ie的 currentStyle

当你请求上面的一些属性的时候,浏览器为了给你最精确的值,需要flush队列,因为队列中可能会有影响到这些值的操作。

如何减少回流、重绘

减少回流、重绘其实就是需要减少对render tree的操作,并减少对一些style信息的请求,尽量利用好浏览器的优化策略。具体方法有:

1. 不要1个1个改变元素的样式属性,最好直接改变className,但className是预先定义好的样式,不是动态的,如果你要动态改变一些样式,则使用cssText来改变,见下面代码:

// 不好的写法  var left = 1;  var top = 1;  el.style.left = left + "px";  el.style.top  = top  + "px";   // 比较好的写法   el.className += " className1";   // 比较好的写法   el.style.cssText += "; left: " + left + "px; top: " + top + "px;";

2. 让要操作的元素进行"离线处理",处理完后一起更新,这里所谓的"离线处理"即让元素不存在于render tree中,比如:

a) 使用documentFragment或div等元素进行缓存操作,这个主要用于添加元素的时候,大家应该都用过,就是先把所有要添加到元素添加到1个div(这个div也是新加的),

最后才把这个div append到body中。

b) 先display:none 隐藏元素,然后对该元素进行所有的操作,最后再显示该元素。因对display:none的元素进行操作不会引起回流、重绘。所以只要操作只会有2次回流。

3 不要经常访问会引起浏览器flush队列的属性,如果你确实要访问,就先读取到变量中进行缓存,以后用的时候直接读取变量就可以了,见下面代码:

// 别这样写,大哥  for(循环) {      elel.style.left = el.offsetLeft + 5 + "px";      elel.style.top  = el.offsetTop  + 5 + "px";  }   // 这样写好点  var left = el.offsetLeft,top  = el.offsetTop,s = el.style;  for(循环) {      left += 10;      top  += 10;      s.left = left + "px";      s.top  = top  + "px";  }

4. 考虑你的操作会影响到render tree中的多少节点以及影响的方式,影响越多,花费肯定就越多。比如现在很多人使用jquery的animate方法移动元素来展示一些动画效果,想想下面2种移动的方法:

// block1是position:absolute 定位的元素,它移动会影响到它父元素下的所有子元素。  // 因为在它移动过程中,所有子元素需要判断block1的z-index是否在自己的上面,  // 如果是在自己的上面,则需要重绘,这里不会引起回流  $("#block1").animate({left:50});  // block2是相对定位的元素,这个影响的元素与block1一样,但是因为block2非绝对定位  // 而且改变的是marginLeft属性,所以这里每次改变不但会影响重绘,  // 还会引起父元素及其下元素的回流  $("#block2").animate({marginLeft:50});

实例测试

最后用2个工具对上面的理论进行一些测试,这2个工具是在我 "web 性能测试工具推荐" 文章中推荐过的工具,分别是:dynaTrace(测试ie),Speed Tracer(测试Chrome)。

第一个测试代码不改变元素的规则,大小,位置。只改变颜色,所以不存在回流,仅测试重绘,代码如下:

<body>     <script type="text/javascript">         var s = document.body.style;          var computed;          if (document.body.currentStyle) {            computed = document.body.currentStyle;          } else {            computed = document.defaultView.getComputedStyle(document.body, '');          }      function testOneByOne(){        s.color = 'red';;        tmp = computed.backgroundColor;        s.color = 'white';        tmp = computed.backgroundImage;        s.color = 'green';        tmp = computed.backgroundAttachment;      }            function testAll() {        s.color = 'yellow';        s.color = 'pink';        s.color = 'blue';                tmp = computed.backgroundColor;        tmp = computed.backgroundImage;        tmp = computed.backgroundAttachment;      }      </script>          color test <br />     <button onclick="testOneByOne()">Test One by One</button>     <button onclick="testAll()">Test All</button> </body>

testOneByOne 函数改变3次color,其中每次改变后调用getComputedStyle,读取属性值(按我们上面的讨论,这里会引起队列的flush),testAll同样是改变3次color,但是每次改变后并不马上调用getComputedStyle。

我们先点击Test One by One按钮,然后点击 Test All,用dynaTrace监控如下:

上图可以看到我们执行了2次button的click事件,每次click后都跟一次rendering(页面重绘),2次click函数执行的时间都差不多,0.25ms,0.26ms,但其后的rendering时间就相差一倍多。(这里也可以看出,其实很多时候前端的性能瓶颈并不在于JS的执行,而是在于页面的呈现,这种情况在用JS做到富客户端中更为突出)。我们再看图的下面部分,这是第一次rendering的详细信息,可以看到里面有2行是 Scheduleing layout task,这个就是我们前面讨论过的浏览器优化过的队列,可以看出我们引发2次的flush。

再看第二次rendering的详细信息,可以看出并没有Scheduleing layout task,所以这次rendering的时间也比较短。

测试代码2:这个测试跟第一次测试的代码很类似,但加上了对layout的改变,为的是测试回流。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body>     <script type="text/javascript">         var s = document.body.style;          var computed;          if (document.body.currentStyle) {            computed = document.body.currentStyle;          } else {            computed = document.defaultView.getComputedStyle(document.body, '');          }      function testOneByOne(){        s.color = 'red';        s.padding = '1px';        tmp = computed.backgroundColor;        s.color = 'white';        s.padding = '2px';        tmp = computed.backgroundImage;        s.color = 'green';        s.padding = '3px';        tmp = computed.backgroundAttachment;      }            function testAll() {        s.color = 'yellow';        s.padding = '4px';        s.color = 'pink';        s.padding = '5px';        s.color = 'blue';        s.padding = '6px';                tmp = computed.backgroundColor;        tmp = computed.backgroundImage;        tmp = computed.backgroundAttachment;      }      </script>          color test <br />     <button onclick="testOneByOne()">Test One by One</button>     <button onclick="testAll()">Test All</button> </body>

用dynaTrace监控如下:

相信这图不用多说大家都能看懂了吧,可以看出有了回流后,rendering的时间相比之前的只重绘,时间翻了3倍了,可见回流的高成本性啊。

大家看到时候注意明细处相比之前的多了个 Calcalating flow layout。

最后再使用Speed Tracer测试一下,其实结果是一样的,只是让大家了解下2个测试工具:

测试1:

图上第一次点击执行2ms(其中有50% 用于style Recalculation), 第二次1ms,而且第一次click后面也跟了2次style Recalculation,而第二次点击却没有style Recalculation。

但是这次测试发现paint重绘的时间竟然是一样的,都是3ms,这可能就是chrome比IE强的地方吧。

测试2:

从图中竟然发现第二次的测试结果在时间上跟第一次的完全一样,这可能是因为操作太少,而chrome又比较强大,所以没能测试明显结果出来,

但注意图中多了1个紫色部分,就是layout的部分。也就是我们说的回流。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn