What are differences to consider when choosing between the .insertAdjacentHTML and .innerHTML methods? What are compelling use-cases for each? Which has better performance and in what situations? How does .innerHTML work? Are there other alternatives?
There are a few benefits .insertAdjacentHTML has over .innerHTML. The first of which is performance. In a benchmarking test performed, .innerHTML appended slightly over 200 Twitter tweets in five full seconds. insertAdjacentHTML, on the other hand appended nearly 30,000 in the same time-frame. The more data that needed to be appended, the worse .innerHTML performed. Note however, in this case, data was appended using .innerHTML +=.
Another benefit is control. .insertAdjacentHTML provides you with control over where you want to append data, while `.innerHTML does not.
The final benefit of .insertAdjacentHTML is it does not corrupt the DOM. Here is how .innerHTML += works.
.innerHTML by serializing the descendants of
element..innerHTML =.Other alternatives to .innerHTML are the .insertBefore method, which as its name suggests inserts a node as a child before another node, as well as the .appendChild method which inserts a child node as the last node.
.insertAdjacentHTML is something of a multi-functional tool seeing as it can perform the jobs of .innerHTML, .insertBefore, as well as .appendChild.
Sources: https://hacks.mozilla.org/2011/11/insertadjacenthtml-enables-faster-html-snippet-injection/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With