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.

Writing through innerHTML parses HTML again. If the change affects layout, the browser may recalculate layout (reflow) and repaint. Doing that thousands of times in a loop can make the page slow. Not every DOM write recalculates the whole page.

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).

const list = document.getElementById("list");
for (let 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.

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

document.createDocumentFragment() can hold the new nodes and be appended once. Whether that is faster than one innerHTML assignment was not remeasured. The loop must not increment i a second time, or it creates only half of the items. textContent sets text without parsing HTML.

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

Feedback about page:

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



Table Of Contents