Document Fragments are something I haven't seen used much in the wild but is something that can make your web pages faster and is available in all modern web browsers. It's part of the W3C DOM specification and support goes way back to Internet Explorer 6.
A Document Fragment is an in-memory version of the DOM (Document Object Model) that can easily be added to a web page (DOM tree). Adding a Document Fragment to the DOM only incurs the overhead of a single page reflow rather than reflowing the page every single time an element is added to it.
Here's some example code that doesn't utilize document fragments; it adds 100,000 divs directly to the DOM.
In case you're curious, here's the CSS:
Here's an explanation of the code:
- All of the code is wrapped in an IIFE (Immediately Invoked Function Expression).
- The function named startup is executed first.
- The elements representing the content is retrieved by calling function getContentElements.
- The function getContentElements, obtains 100,000 elements by calling function getContentElementsForRow until the desired number elements is obtained.
- The function getContentElementsForRow creates five divs each containing a unique number, a different background color and a width of 20%.
- The start date/time is obtained.
- Each of the 100,000 divs are added to the content div.
- The end date/time is obtained.
- The duration is output.
Here's the beginning of the web page:
Here's the bottom of the web page:
The web page took a total of 52 milliseconds to add the 100,000 divs to the DOM and render them.
I ran the test ten times and here are the results: 52, 56, 44, 52, 56, 53, 58, 51, 54 and 52 milliseconds for an average of 52.8 milliseconds.
Here's the code refactored to utilize document fragments instead of adding each div directly to the DOM:
The main difference is the addition of function createFragment which creates a document fragment and adds the passed elements to it. Also, function showElement is only called once since all of the content is contained in one document fragment.
I ran the test ten times and here are the results: 53, 51, 48, 53, 52, 51, 54, 52, 49 and 51 milliseconds for an average of 51.4 milliseconds.
In the end, the document fragment optimization only realized a performance improvement of 1.4 milliseconds (52.8 - 51.4).
John Resig wrote a blog post about document fragments back in 2008 demonstrating that they were much faster than interacting with the DOM directly. You can find the blog post here:
John Resig on DOM Document Fragments
In a StackOverflow post dating back to 2013, it was concluded that document fragments didn't offer much in the way of performance improvements. You can find the post here:
Does Using a Document Fragment Really Improve Performance
In the StackOverflow post, they refer to an example that demonstrates fragments are not significantly faster as follows:
Document Fragment Test
So, do document fragments still make web pages faster? No, it doesn't appear so.