Table of Contents
2. Optimization
2.1 Reduce access" >2.1 Reduce access
2.1.1 Cache NodeList" >2.1.1 Cache NodeList
2.1.2 Change the selector
2.1.3 Avoid unnecessary loops
2.1.4 Event Delegate
2.2 Reduce redrawing and rearrangement" >2.2 Reduce redrawing and rearrangement
2.2.1 Change multiple styles of a DOM node" >2.2.1 Change multiple styles of a DOM node
2.2.2 Modify the dom node styles in batches
3、总结
Home Web Front-end JS Tutorial JavaScript optimized DOM

JavaScript optimized DOM

Mar 19, 2018 pm 04:27 PM
javascript js optimization

This time I will bring you JavaScript to optimize the DOM, and what are the precautions for optimizing the DOM in JavaScript. The following is a practical case, let’s take a look.

Optimizing DOM must start with redrawing and rearrangement, long long ago...

1. Redrawing and rearrangement

1.1 What are redrawing and rearranging

Redrawing refers to some style modifications, and the position and size of the elements have not changed;

Rearrangement means that the position or size of an element has changed, and the browser needs to recalculate the rendering tree. After the new rendering tree is established, the browser will redraw the affected elements.

1.2 Browser rendering page

When you go to an interview, you will always be asked a question, that is, "Enter a line of url into the browser." What happened?", the answer to this question involves not only network knowledge but also the issue of browser rendering of the page. When our browser receives the page responded from the server, it starts rendering line by line. When it encounters css, it will asynchronously calculate the attribute value, and then continue to parse the dom downwards. After the parsing is completed, a DOM tree will be formed, which will be asynchronousThe calculated style (style box) is combined with the DOM tree to form a Render tree, which is then drawn on the page by the browser. 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 determines whether to redraw and reflow based on the js.

1.3 Reasons for redrawing and rearrangement

Factors that cause redrawing:

Factors causing rearrangement:

In short, you must know that js is single-threaded , redrawing and reflowing will block user operations and affect the performance of the web page. When a page is redrawn and reflowed multiple times, such as writing a timer to change the width and height of page elements every 500ms, the page may become It’s getting more and more laggy, so we need to reduce redrawing and reflowing as much as possible. Then our optimization of DOM is also based on this starting point.

2. Optimization

2.1 Reduce access

Reducing the number of accesses naturally means caching elements, but you must pay attention

var ele = document.getElementById('ele');
Copy after login

This does not cache ele. Each time ele is called, it is equivalent to visiting the node with the ID ele.

2.1.1 Cache NodeList

var foods = document.getElementsByClassName('food');
Copy after login

We can use foods[i] to access the i-th element with class food, but the foods here are not an array , but a NodeList. NodeList is an array-like array that stores some ordered nodes and can access these nodes by position. NodeList objects are dynamic and a document-based query is run on each access. Therefore, we need to minimize the number of visits to NodeList, and we can consider caching the value of NodeList.

// 优化前var lis = document.getElementsByTagName('li');for(var i = 0; i < lis.length; i++) {     // do something...  }// 优化后,将length的值缓存起来就不会每次都去查询length的值var lis = document.getElementsByTagName('li');for(var i = 0, len = lis.length; i < len; i++) {     // do something...  }
Copy after login

And because NodeList changes dynamically, if it is not cached, it may cause an infinite loop, such as adding elements while getting the length of NodeList.

2.1.2 Change the selector

There are two most common ways to get elements, getElementsByXXX() and queryselectorAll(). The difference between these two selectors is very big. The former is to get Dynamic collection, the latter is to obtain a static collection, for example.

// 假设一开始有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, 4var lis = document.querySelector('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
Copy after login

Operations on static collections will not cause re-querying of documents, which is more optimized than dynamic collections.

2.1.3 Avoid unnecessary loops

// 优化前
for(var i = 0; i < 10; i++) {
    document.getElementById('ele').innerHTML += 'a';
Copy after login
} 
// 优化后 
var str = ''; 
for(var i = 0; i < 10; i++) {
    str += 'a'; 
}
document.getElementById('ele').innerHTML = str;
Copy after login

The pre-optimized code accesses the ele element 10 times, while the optimized code only accesses it once, which greatly improves efficiency.

2.1.4 Event Delegate

The event functions in js are all objects. If there are too many event functions, they will occupy a lot of memory, and the more DOM elements that are bound to the event, the more time it will take to access the dom. times, there will also be a delay in the interactive readiness time of the page. Therefore, event delegation was born. Event delegation uses event bubbling. Only one event processing program can manage all events of a certain type.

// 事件委托前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')[0];
ul.onclick = function(event) {
   console.log(event.target.innerHTML);
};
Copy after login

Before event delegation, we visited lis.length times li, but after using event delegation, we only visited ul once.

2.2 Reduce redrawing and rearrangement

2.2.1 Change multiple styles of a DOM node

We want to change the width and height of a p element. The usual approach can be like this

 p = document.getElementById('p1'
Copy after login

The above operation changed two attributes of the element, accessed the dom three times, and triggered two rearrangements and two rearrangements. painted. We have said that optimization is to reduce the number of visits and the number of redraws and rearrangements. From this starting point, can we only access the element once and reduce the number of rearrangements to 1? Obviously it is possible, we can write a class in css

/* css
.change {
    width: 220px;
    height: 300px;
}*/document.getElementById('p').className = 'change';
Copy after login

This way we can operate multiple styles at one time

2.2.2 Modify the dom node styles in batches

Above The code is for a DOM node. What if we want to change the style of a DOM collection?

The first method that comes to mind is to traverse the collection and add a className to each node. Think about it again, doesn't this mean that you have visited the DOM node multiple times? Think about the difference between the DOM tree and the rendering tree mentioned at the beginning of the article. If the display attribute of a node is none, then this node will not exist in the render tree, which means that the operation of this node will not affect the render tree and will not cause Redrawing and rearranging, based on this idea we can achieve optimization:

  • Display the parent element of the collection to be modified: none;

  • 之后遍历修改集合节点

  • 将集合父元素display: block;

// 假设增加的class为.changevar lis = document.getElementsByTagName('li');  
var ul = document.getElementsByTagName('ul')[0];
ul.style.display = 'none';for(var i = 0; i < lis.length; i++) {
    lis[i].className = 'change';  
}
ul.style.display = 'block';
Copy after login

3、总结

  • 减少访问dom的次数

    • 缓存节点属性值

    • 选择器的使用

    • 避免不必要的循环

    • 事件委托

  • 减少重绘与重排

    • 使用className改变多个样式

    • 使父元素脱离文档流再恢复

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue的计算属性

Webpack模块的使用

The above is the detailed content of JavaScript optimized DOM. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

See all articles