Let’s review the previous article High-Performance JavaScript DOM Programming . It mainly proposes two optimizations. One is to minimize DOM access and put the calculation on the ECMAScript side. The other is to cache as much as possible. Local variables, such as length, etc. Finally, two new APIs querySelector() and querySelectorAll() are introduced, which can be used boldly when making combined selections. This article mainly talks about probably the most time-consuming part of DOM programming, rearrangement and redrawing .
1. What is reflow and redraw
After the browser downloads all the components in the page-HTML tags, JavaScript, CSS, and images, it will parse and generate two internal data structures-DOM tree and rendering tree.
The DOM tree represents the page structure, and the rendering tree represents how DOM nodes are displayed. Each node in the DOM tree that needs to be displayed has at least one corresponding node in the rendering tree (a hidden DOM element with a display value of none has no corresponding node in the rendering tree). The nodes in the rendering tree are called "frames" or "boxes", which conform to the definition of the CSS model, which understands page elements as a box with padding, margins, borders, and position. Once the DOM and render tree are constructed, the browser begins displaying (drawing) page elements.
When DOM changes affect the geometric properties (width or height) of an element, the browser needs to recalculate the geometric properties of the element, and the geometric properties and positions of other elements will also be affected. The browser invalidates the affected portion of the render tree and reconstructs the render tree. This process is called rearrangement. After completing the reflow, the browser will redraw the affected part to the screen, a process called redraw. Due to the browser's flow layout, the calculation of the render tree usually only needs to be traversed once. With the exception of table and its internal elements, it may require multiple calculations to determine the attributes of its nodes in the rendering tree, which usually takes 3 times the time of equivalent elements. This is one reason why we should avoid using tables for layout.
Not all DOM changes will affect geometric properties. For example, changing the background color of an element will not affect the width and height of the element. In this case, only redrawing will occur.
2. How much is the cost of rearrangement and redrawing
How expensive are reflows and repaints? Let's go back to the previous example of crossing the bridge. If you are careful, you may find that the thousand-fold time difference is not caused by "crossing the bridge". Each "crossing the bridge" is actually accompanied by rearrangement and redrawing. And most of the energy consumption is here!
var times = 15000; // code1 每次过桥+重排+重绘 console.time(1); for(var i = 0; i < times; i++) { document.getElementById('myDiv1').innerHTML += 'a'; } console.timeEnd(1); // code2 只过桥 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 doesn’t lie. As you can see, accessing the DOM multiple times is not worth mentioning for the time it takes to reflow and redraw it.
3. When does the rearrangement occur
Obviously, every rearrangement will inevitably lead to redrawing. So, under what circumstances will rearrangement occur?
1. Add or delete visible DOM elements
2. Change element position
3. Element size changes
4. Element content changes (for example: a text is replaced by another image of a different size)
5. Page rendering initialization (this cannot be avoided)
6. Browser window size change
These are all obvious. Maybe you have already had this experience. Constantly changing the size of the browser window causes the UI to respond slowly (some low versions of IE even hang directly). Now you may suddenly realize that, yes, it is exactly the same. It’s caused by rearrangement and redrawing again and again!
4. Queuing and refreshing of render tree changes
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 has changed three times, and each change will cause rearrangement and redrawing, so there are three rearrangement and redrawing processes in total, but the browser is not so stupid, it will modify it three times." "Save" (most browsers optimize the reordering process by queuing modifications and executing them in batches), done in one go! However, there are times when you may (often unknowingly) force a queue flush and require a scheduled task to execute immediately. The operation of obtaining layout information will cause the queue to be refreshed, such as:
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';
因为offsetHeight属性需要返回最新的布局信息,因此浏览器不得不执行渲染队列中的“待处理变化”并触发重排以返回正确的值(即使队列中改变的样式属性和想要获取的属性值并没有什么关系),所以上面的代码,前两次的操作会缓存在渲染队列中待处理,但是一旦offsetHeight属性被请求了,队列就会立即执行,所以总共有两次重排与重绘。所以尽量不要在布局信息改变时做查询。
5、最小化重排和重绘
我们还是看上面的这段代码:
var ele = document.getElementById('myDiv'); ele.style.borderLeft = '1px'; ele.style.borderRight = '2px'; ele.style.padding = '5px';
三个样式属性被改变,每一个都会影响元素的几何结构,虽然大部分现代浏览器都做了优化,只会引起一次重排,但是像上文一样,如果一个及时的属性被请求,那么就会强制刷新队列,而且这段代码四次访问DOM,一个很显然的优化策略就是把它们的操作合成一次,这样只会修改DOM一次:
var ele = document.getElementById('myDiv'); // 1. 重写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、fragment元素的应用
看如下代码,考虑一个问题:
<ul id='fruit'> <li> apple </li> <li> orange </li> </ul>
如果代码中要添加内容为peach、watermelon两个选项,你会怎么做?
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);
很容易想到如上代码,但是很显然,重排了两次,怎么破?前面我们说了,隐藏的元素不在渲染树中,太棒了,我们可以先把id为fruit的ul元素隐藏(display=none),然后添加li元素,最后再显示,但是实际操作中可能会出现闪动,原因这也很容易理解。这时,fragment元素就有了用武之地了。
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);
文档片段是个轻量级的document对象,它的设计初衷就是为了完成这类任务——更新和移动节点。文档片段的一个便利的语法特性是当你附加一个片断到节点时,实际上被添加的是该片断的子节点,而不是片断本身。只触发了一次重排,而且只访问了一次实时的DOM。
7、让元素脱离动画流
用展开/折叠的方式来显示和隐藏部分页面是一种常见的交互模式。它通常包括展开区域的几何动画,并将页面其他部分推向下方。
一般来说,重排只影响渲染树中的一小部分,但也可能影响很大的部分,甚至整个渲染树。浏览器所需要重排的次数越少,应用程序的响应速度就越快。因此当页面顶部的一个动画推移页面整个余下的部分时,会导致一次代价昂贵的大规模重排,让用户感到页面一顿一顿的。渲染树中需要重新计算的节点越多,情况就会越糟。
使用以下步骤可以避免页面中的大部分重排:
使用绝对位置定位页面上的动画元素,将其脱离文档流
让元素动起来。当它扩大时,会临时覆盖部分页面。但这只是页面一个小区域的重绘过程,不会产生重排并重绘页面的大部分内容。
当动画结束时恢复定位,从而只会下移一次文档的其他元素
总结
重排和重绘是DOM编程中耗能的主要原因之一,平时涉及DOM编程时可以参考以下几点:
尽量不要在布局信息改变时做查询(会导致渲染队列强制刷新)
同一个DOM的多个属性改变可以写在一起(减少DOM访问,同时把强制渲染队列刷新的风险降为0)
如果要批量添加DOM,可以先让元素脱离文档流,操作完后再带入文档流,这样只会触发一次重排(fragment元素的应用)
将需要多次重排的元素,position属性设为absolute或fixed,这样此元素就脱离了文档流,它的变化不会影响到其他元素。例如有动画效果的元素就最好设置为绝对定位。
以上就是高性能JavaScript 重排与重绘的全部介绍内容,大家可以结合上一篇高性能JavaScript DOM编程(1)一起学习,
希望这两篇文章可以帮到大家,解决大家这方面的疑惑。