Home > Article > Web Front-end > How to optimize Dom nodes
This article will introduce to you the optimization plan of Dom node. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
DOM operation has the greatest impact on performance because it leads to browser redrawing and reflow. We all know that changes to the page UI are achieved through DOM operations. DOM Although many APIs are provided to facilitate us to operate the DOM, the cost of DOM operations is very high, and most of the performance bottlenecks of the page's front-end code are concentrated on DOM operations. Therefore, a major focus of front-end performance optimization is the optimization of DOM operations.
Browser rendering mechanism:
Browser renders page
Browser parses HTML document source code, and then construct a DOM tree, and calculate it asynchronously when encountering styles.
The asynchronously calculated style is synthesized with the DOM tree to build the render tree.
Layout the render tree.
Draw the render tree.
The difference between the DOM tree and the render tree is that nodes with the style display:none; will be in the DOM tree but not in the render tree. After the browser draws it, it starts to parse the js file and determine whether to redraw and reflow based on the js.
Operations that occur when page changes occur:
js is single-threaded, redrawing and reflowing will block user operations and affect the performance of the web page
1 , change multiple dom styles, use class instead of style to reduce multiple triggers of reflow and redraw
Example: change the width and height of dom elements
var dom = document.getElementById('box') dom.style.width = '300px' dom.style.height = '300px'//访问了三次dom,触发了两次回流和两次重绘
After optimization:
.change { width: 300px; height: 300px; } document.getElementById('p').className = 'change'//只触发一次
2. Modify the list type in batches, break away from the document flow and then restore it. The nodes with the style display:none; will be in the DOM tree but not in the rendering tree and will not cause redraw reflow.
If we want to add a class to each DOM child node in a DOM collection, we can traverse and add the class to each node, thus triggering multiple redraws and reflows.
/* //需要加入的样式 .change { width: 300px; height: 300px; } */ var ul = document.getElementsByTagName('ul') var lis = document.getElementsByTagName('li') ul.style.display = 'none' for(var i = 0; i < lis.length; i++) { lis[i].className = 'change'; } ul.style.display = 'block'
3. DocumentFragment
Virtual DOM is actually an object. js provides the reateDocumentFragment() method to create an empty virtual node object. The DocumentFragment node does not belong to the document tree. When multiple DOM elements need to be added, if these elements are added to the DocumentFragment first, and then the DocumentFragment object is added to the rendering tree, the number of times the page renders the DOM will be reduced, and the efficiency will be significantly improved.
var frag = document.createDocumentFragment() //创建一个虚拟节点对象 for(var i = 0; i < 10; i++) { var li = document.createElement("li") li.innerHTML = '我是第' + i + 1 + '个元素' frag.appendChild(li) //将li元素加到虚拟节点对象上 } ul.appendChild(frag) //将虚拟节点对象加到ul上
Others
1. Event delegation, using browser events and bubble capture to reduce page event binding, we can Specify an event handler to manage all events of a certain type. Too many event functions will occupy a lot of memory, and the more DOM elements bound to the event will increase the number of DOM visits, and the interactive readiness time of the page will also be delayed.
// 事件委托前 var lis = document.getElementsByTagName('li') for(var i = 0; i < lis.length; i++) { lis[i].onclick = function() { console.log(this.innerHTML) }} // 利用浏览器事件通过父元素委托事件给子元素 var ul = document.getElementsByTagName('ul')ul.onclick = function(event) { //也可以做判断给指定的子元素绑定事件 console.log(event.target.innerHTML)};
2. Optimization in the loop reduces the number of dom operations
//例子1:减少在计算过程中操作dom // 优化前,访问了好多次dom,这些都是细节问题,有经验的绕过,小白平常多注意就行 for(var i = 0; i < 10; i++) { document.getElementById('el').innerHTML += '1'} // 优化后 var str = ''for(var i = 0; i < 10; i++) { str += '1'}document.getElementById('el').innerHTML = str/
If you look at it this way, you will not be able to experience the effect of the cache node length. Please see the example below
//不缓存 var ps = document.getElementsByTagName("p"), i, p; for( i=0; i<ps.length; i++ ){ p = document.createElement("p"); document.body.appendChild("p"); }造成死循环,每次执行for循环都会动态获取ps的长度,而我们每次进入循环都增加了一个DOM(p),ps的长度也+1. //缓存 var ps = document.getElementsByTagName("p"), i, p,len; for( i=0;len=ps.length;i<len; i++ ){ p = document.createElement("p"); document.body.appendChild("p"); }//使用变量保存ps的长度。
3. Differences in selectors
There are two most common ways to obtain elements, getElementsByXXX() and queryselectorAll(). The difference between these two selectors is very big. The former is to obtain a dynamic collection, the latter is to obtain a static collection
// 假设一开始有2个livar lis = document.getElementsByTagName('li') // 动态集合 var ul = document.getElementsByTagName('ul')[0] for(var i = 0; i < 3; i++) { console.log(lis.length) var newLi = document.createElement('li') ul.appendChild(newLi)}// 输出结果:2, 3, 4 // 优化后 var lis = document.querySelectorAll('li') // 静态集合 var ul = document.getElementsByTagName('ul')[0] for(var i = 0; i < 3; i++) { console.log(lis.length) var newLi = document.createElement('li') ul.appendChild(newLi)}// 输出结果:2, 2, 2
The operation of the static collection will not cause re-query of the document, which is more optimized than the dynamic collection.
Recommended learning: javascript video tutorial
The above is the detailed content of How to optimize Dom nodes. For more information, please follow other related articles on the PHP Chinese website!