Home > Web Front-end > JS Tutorial > body text

How to optimize Dom nodes

醉折花枝作酒筹
Release: 2021-04-12 11:16:39
Original
2414 people have browsed it

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.

How to optimize Dom nodes

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:

How to optimize Dom nodes
Browser renders page
How to optimize Dom nodes

  1. Browser parses HTML document source code, and then construct a DOM tree, and calculate it asynchronously when encountering styles.

  2. The asynchronously calculated style is synthesized with the DOM tree to build the render tree.

  3. Layout the render tree.

  4. 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.

Reflow·Redraw

Operations that occur when page changes occur:

  1. Reflow: The browser engine discovers that a certain node in the render tree has changed, affecting the layout, which requires Go back and re-render, we call this rollback process reflow. Reflow will recurse downward from this root frame, calculating the geometric dimensions and positions of all nodes in sequence.
  2. Redraw: Change the background color, text color, border color, etc. of an element without affecting the DOM layout of the page.

js is single-threaded, redrawing and reflowing will block user operations and affect the performance of the web page

Optimization: Reduce the number of reflow redraws

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,触发了两次回流和两次重绘
Copy after login

After optimization:

.change {
    width: 300px;
    height: 300px;
    }
    document.getElementById('p').className = 'change'//只触发一次
Copy after login

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 = &#39;change&#39;;
     }
     ul.style.display = &#39;block&#39;
Copy after login

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 = &#39;我是第&#39; + i + 1 + &#39;个元素&#39;		
    frag.appendChild(li)  //将li元素加到虚拟节点对象上
    } 			
    ul.appendChild(frag)  //将虚拟节点对象加到ul上
Copy after login

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(&#39;li&#39;)
for(var i = 0; i < lis.length; i++) {
   lis[i].onclick = function() {
      console.log(this.innerHTML)
   }}    // 利用浏览器事件通过父元素委托事件给子元素
   var ul = document.getElementsByTagName(&#39;ul&#39;)ul.onclick = function(event) {
	//也可以做判断给指定的子元素绑定事件
   console.log(event.target.innerHTML)};
Copy after login

2. Optimization in the loop reduces the number of dom operations

//例子1:减少在计算过程中操作dom
// 优化前,访问了好多次dom,这些都是细节问题,有经验的绕过,小白平常多注意就行
for(var i = 0; i < 10; i++) {
    document.getElementById(&#39;el&#39;).innerHTML += &#39;1&#39;} 
    // 优化后 
    var str = &#39;&#39;for(var i = 0; i < 10; i++) {
    str += &#39;1&#39;}document.getElementById(&#39;el&#39;).innerHTML = str/
Copy after login

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的长度。
Copy after login

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(&#39;li&#39;)  // 动态集合
var ul = document.getElementsByTagName(&#39;ul&#39;)[0]
 for(var i = 0; i < 3; i++) {
    console.log(lis.length)
    var newLi = document.createElement(&#39;li&#39;)
    ul.appendChild(newLi)}// 输出结果:2, 3, 4
    // 优化后
    var lis = document.querySelectorAll(&#39;li&#39;)  // 静态集合 
    var ul = document.getElementsByTagName(&#39;ul&#39;)[0]
 for(var i = 0; i < 3; i++) {
    console.log(lis.length)
    var newLi = document.createElement(&#39;li&#39;)
    ul.appendChild(newLi)}// 输出结果:2, 2, 2
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!