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, 2The 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!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython 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 vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







