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.
Reflow·Redraw
Operations that occur when page changes occur:
- 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.
- 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,触发了两次回流和两次重绘
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software