This article illustrates the DOM interaction techniques for JavaScript performance optimization. Share to everyone for your reference, specific as follows:
Dom is undoubtedly the slowest part of JavaScript in all aspects. Dom operations and interactions take a lot of time because they often need to render the entire page or part of it again. Understanding how to optimize interaction with the DOM can greatly improve the speed at which scripts are completed.
1. Minimizing DOM Updates
Look at the following example:
var list = document.getElementById ("ul");
for (Var i=0 i < i++) {
var item = document.createelement ("li");
Item.appendchild (document.createTextNode ("item" + i));
List.appendchild (item);
}
This code adds 10 items to the list. When you add each item, there are two DOM updates. A total of 20 DOM updates are required.
We can use document fragmentation to minimize DOM updates.
var list = document.getElementById ("ul");
var fragment = Document.createdocumentfragment ();
for (Var i=0 i < i++) {
var item = document.createelement ("li");
Item.appendchild (document.createTextNode ("item" + i));
Fragment.appendchild (item);
}
List.appendchild (fragment);
More about document fragmentation, as detailed in the previous article "JavaScript Document fragmentation operation Case Analysis"
2. Use innerHTML
For larger DOM changes, use innerHTML faster than createelement () and appendchild ().
var list = document.getElementById ("ul");
var html = "";
for (Var i=0 i < i++) {
html = "<li>item" + i + "<li>";
}
list.innerhtml = html;
3. Use Event Delegation
As detailed in the article "JavaScript performance Optimization event delegate Example"
4. Pay attention to NodeList
Minimizing the number of accesses to nodelist can greatly improve the performance of the script because a document-based query is run every time the nodelist is accessed.
var IMGs = document.getelementsbytagname ("img");
For (Var i=0, len=imgs.length i < Len; i++) {
var image = Imgs[i];
More code
}
//The key here is that length is stored in Len variable, not every time to access the NodeList length property. When using NodeList in the loop, Imgs[i] is placed in the image variable to avoid multiple calls to the nodelist in the loop;
For more on NodeList, see the previous article, "NodeList as an array in JavaScript"
I hope this article will help you with JavaScript programming.