Document fragment — The lesser known superpower of Javascript
Photo by Pankaj Patel on Unsplash
Page speed of our websites is important. A faster website will more likely improve the conversion rate and search engine rankings of the website. Even though your website has great user experience, it would still mean less if your website is super slow. Walmart once mentioned that every 1 second improvement in their website speed led to a 2% increase in their conversions. There are several such examples from many technology companies that co-relates Web Performance to Business Performance. 💸
If your app becomes sluggish and you suspect it to be the code, then it is most likely the HTML that is slowing it down or the DOM manipulations from your JS Code. Even in the web apps built using the most modern frameworks like React, it is most likely the unsafe handling of component re-renders that is making your app slower. 🐌
Changing actual DOM is an expensive operation and one of the reason modern frameworks use Virtual DOM is to make these operations less expensive with better change detection cycles and diffing algorithms. Document fragment is one such interface that we can use in vanilla JS to improve the performance of our DOM operations in an application. Document fragment is a fragment of the Document object and is not the part of the actual DOM. Using document fragment effectively will reduce the interactions with actual DOM, thus improving your app performance.
Lets talk numbers… 🤖
I have performed a jsbench test and added 10000 list items dynamically with and without document fragment. You can clearly see how the same code is faster when using document fragment.
So, what is the difference?
In the first approach, you are accessing the actual DOM object(list) only once to add a fragment of DOM to it, however in the second snippet, you are changing actual DOM(list) 10,000 times and that makes this approach slower. 🐢
Inclusion of this simple concept does wonders in your application if it involves DOM heavy operations in your code, and Document fragment was rarely/never used in all the code bases I have seen until now. Thus, it has been a secret superpower of JavaScript for me that not many developers use even today.
References:
MDN — https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
Browser compatibility — https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment#browser_compatibility
Top comments (0)