Limit DOM Updates

suggest change

A common mistake seen in JavaScript when run in a browser environment is updating the DOM more often than necessary.

The issue here is that every update in the DOM interface causes the browser to re-render the screen. If an update changes the layout of an element in the page, the entire page layout needs to be re-computed, and this is very performance-heavy even in the simplest of cases. The process of re-drawing a page is known as reflow and can cause a browser to run slowly or even become unresponsive.

The consequence of updating the document too frequently is illustrated with the following example of adding items to a list.

Consider the following document containing a <ul> element:

<!DOCTYPE html>
<html>
    <body>
        <ul id="list"></ul>
    </body>
</html>

We add 5000 items to the list looping 5000 times (you can try this with a larger number on a powerful computer to increase the effect).

var list = document.getElementById("list");
for (var i = 1; i <= 5000; i++) {             
    list.innerHTML += `<li>item ${i}</li>`;  // update 5000 times
}

In this case, the performance can be improved by batching all 5000 changes in one single DOM update.

var list = document.getElementById("list");
var html = "";
for (var i = 1; i <= 5000; i++) {
    html += `<li>item ${i}</li>`;
}
list.innerHTML = html;     // update once

The function document.createDocumentFragment() can be used as a lightweight container for the HTML created by the loop. This method is slightly faster than modifying the container element’s innerHTML property (as shown below).

var list = document.getElementById("list");
var fragment = document.createDocumentFragment();
for (var i = 1; i <= 5000; i++) {
    li = document.createElement("li");
    li.innerHTML = "item " + i;
    fragment.appendChild(li);
    i++;
}
list.appendChild(fragment);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Performance Tips:
* Limit DOM Updates

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
58 Performance Tips
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde