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.
CLICK HERE to find out more related problems solutions.