This article describes the DOM interactive operation skills of JavaScript performance optimization. Share it for your reference, as follows:
In all aspects of javascript, DOM is undoubtedly the slowest part. DOM operations and interactions take a lot of time because they often require re-rendering the entire page or part of it. Understanding how to optimize interaction with DOM can greatly improve script completion speed.
1. Minimize DOM updates
See the following example:
var list = ("ul"); for (var i=0; i < 10; i++){ var item = ("li"); (("item" + i)); (item); } //This code adds 10 items to the list. There are two DOM updates when adding each project. A total of 20 DOM updates are required.
We can use document fragmentation to minimize DOM updates.
var list = ("ul"); var fragment = (); for (var i=0; i < 10; i++){ var item = ("li"); (("item" + i)); (item); } (fragment);
For more information about document fragments, please refer to the previous article "Analysis of JavaScript document fragmentation operation examples》
2. Use innerHTML
For larger DOM changes, using innerHTML is faster than createElement() and appendChild().
var list = ("ul"); var html = ""; for (var i=0; i < 10; i++){ html += "<li>item" + i + "<li>"; } = html;
3. Use event delegation
See previous article for detailsDetailed explanation of event delegation instances for javascript performance optimization》
4. Pay attention to NodeList
Minimizing the number of accesses to NodeList can greatly improve script performance, because every time you access NodeList, a document-based query is run.
var imgs = ("img"); for (var i=0, len=; i < len; i++){ var image = imgs[i]; //more code } //The key here is that the length length is stored in the len variable, instead of accessing the length property of the NodeList every time. When using NodeList in a loop, put imgs[i] into the image variable to avoid calling NodeList multiple times in the loop body;
For more information about NodeList, please refer to the previous article "Method of processing NodeList as Array array in javascript》
I hope this article will be helpful to everyone's JavaScript programming.