Search code examples
javascriptfor-loopinnerhtml

Javascript: Does Inner HTML update during the forloop or after the entire loop is run?


I just wanted to improve my e-commerce website performance in terms of appending new items to it. We have a lot of items to display so I'm wondering if this would work. Any help would be greatly appreciated!

for (item of items) {
item_display_div.innerHTML += item; // Would the item_display_div only start updating here?
}
// Or here?

Solution

  • Concatenating onto the innerHTML of an element will force the browser to completely re-parse the HTML markup inside and create new elements. If you do that many times in a loop, it could be expensive. Example:

    document.body.innerHTML += '<img src onerror="console.log(`img tag 1 errorred`)">';
    
    document.body.innerHTML += '<img src onerror="console.log(`img tag 2 errorred`)">';

    See how the first <img> tag gets parsed twice - first after the first .innerHTML +=, and again after the second .innerHTML +=.

    Better to use a DocumentFragment - append the elements to the fragment, then append the fragment at the very end.

    Also, whenever you do have to insert plain HTML markup, at least consider using insertAdjacentHTML instead of .innerHTML += - insertAdjacentHTML does not force the container to re-parse any of its elements.