Accessing DOM elements comes at a cost, and modifying DOM elements is even more expensive because it causes the browser to recalculate the page's geometric changes.
Of course, the worst case is accessing the modified element in the loop, especially loop operations on HTML elements collections.
For example:
The code copy is as follows:
<!-- Before optimization-->
<script type="text/javascript">
function innerHTMLLoop () {
for(var count = 0; count < 15000; count++){
document.getElementById('here').innerHTML+='a';
}
}
</script>
This function loops to modify the content of the page element. The problem with this code is that each loop iteration, the element is accessed twice: once read the innerHTML property and once rewrite it.
A more efficient approach is to use local variables to store the updated content and then write it at one time after the loop ends:
The code copy is as follows:
<!-- After optimization-->
<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 the code runs. Therefore, when there are other solutions to replace them, we should try to minimize the number of visits to the DOM.