Reducing the number of DOM accesses improves javascript performance

  • 2020-03-30 02:06:35
  • OfStack

Accessing DOM elements is expensive, and modifying them is more expensive because it causes the browser to recalculate the geometry of the page.

Of course, the worst case scenario is to access the modified elements in a loop, especially the loop operation on the collection of HTML elements.

Such as:
 
<!--  Before optimization  --> 
<script type="text/javascript"> 
function innerHTMLLoop () { 
for(var count = 0; count < 15000; count++){ 
document.getElementById('here').innerHTML+='a'; 
} 
} 
</script> 

This function loops through the contents of a page element. The problem with this code is that with each iteration of the loop, the element is accessed twice: once to read the innerHTML attribute, and once to override it.

A more efficient approach is to use local variables to store the updated content and then write it once after the loop ends:
 
<!--  The optimized  --> 
<script type="text/javascript"> 
function innerHTMLLoop () { 
var content = ''; 
for(var count = 0; count < 15000; count++){ 
content+='a'; 
} 
document.getElementById('here').innerHTML+=content; 
} 
</script> 

The more times you access the DOM, the slower your code will run. Therefore, we want to minimize the number of times we access the DOM when there are alternatives.

Related articles: