When it comes to Javascript, there are many ways you can skin a cat as they say. When it comes to inserting HTML into a page, unless you are using a Javascript library like jQuery or something like React.js or AngularJS, you most likely are using innerHTML.
Even the html()
method in jQuery internally uses the innerHTML property to insert HTML into your element(s), as do many other libraries and frameworks.
When it comes to performance sadly, innerHTML proves just how shitty it actually is when you need to bulk insert some HTML into your page. While the need to insert hundreds or thousands of elements into a page might be pretty niche, it is good to know when limits are being reached.
Enter DOMDocumentFragment. You would be surprised how many developers I meet who do not even know DOMDocumentFragment exists, what it does or when to use it.
The fantastic Mozilla web docs [here](The DocumentFragment interface represents a minimal document object that has no parent. It is used as a light-weight version of Document to store well-formed or potentially non-well-formed fragments of XML.) describe DOMDocumentFragment:
The DocumentFragment interface represents a minimal document object that has no parent. It is used as a light-weight version of Document to store well-formed or potentially non-well-formed fragments of XML.
While the benefits of using DOMDocumentFragment for inserting a few elements might be negligible, you get the benefit or reducing reflows and repaints, keeping performance in your web application high and giving yourself some room to grow.
This old JSPerf test is an oldie but a goodie and clearly shows the MASSIVE performance gains you get using DOMDocumentFragment over a traditional innerHTML call.
However, things tend to get more complicated when it comes to mobile performance. Rather than reiterate things that have been said before, I implore you to read this article and decide if the weird caveats of mobile phone browsers favouring innerHTML over DOMDocumentFragment in a few cases is an issue for you.
Hi there friend.
I gotta disagree. The above test is flawed since innerHTML is used inside each loop.
If you wanna test innerHTML vs DocumentFragment you gotta put the whole HTML string into a var, and then do a single innerHTML affectation.
Here is a better test:
https://jsperf.com/appendchild-vs-documentfragment-vs-innerhtml/24
Which clearly shows that a single innerHTML is the winner.
Best regards brah