How javascript optimizes DOM
This article mainly explains "javascript how to optimize DOM", the explanation content in the article is simple and clear, easy to learn and understand, please follow the idea of Xiaobian slowly in-depth, together to study and learn "javascript how to optimize DOM"!
1. When modifying Dom styles, all modifications should be combined as much as possible and processed at once to reduce the number of rearrangements and rearrangements.
//optimization before const el = document.getElementById('test'); el.style.borderLeft = '1px'; el.style.borderRight = '2px'; el.style.padding = '5px'; //After optimization, modify the style once, so that three rearrangements can be reduced to one rearrangement const el = document.getElementById ('test '); el.style.cssText +='; border-left: 1px ;border-right: 2px; padding: 5px;'
2. When modifying DOM nodes in batches, you can hide DOM nodes, then perform a series of modification operations, and then set them to visible.
//const ele = document.getElementById ('test '); //a series of dom modification operations //Optimization Scheme 1: Set the node to be modified to not be displayed, modify it later, and display the node after the modification is completed, so that only two rearrangement const ele = document.getElementById ('test '); ele.style.display ='none'; //a series of dom modification operations ele.style.display ='block '; //Optimization scheme 2: First create a document fragment (documentFragment), then modify the fragment, and then insert the document fragment into the document. Only when the document fragment is finally inserted into the document will it cause rearrangement, so only one rearrangement will be triggered. const fragment = document.createDocumentFragment(); const ele = document.getElementById ('test '); //a series of dom modification operations ele.appendChild(fragment); Thank you for reading, the above is the "javascript how to optimize DOM" content, after learning this article, I believe that we have a deeper understanding of how to optimize DOM javascript this problem, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!