Using Document Fragments for Performant DOM Operations


First published: 14/08/2024

Whenever you make a change to the DOM, like adding, updating, or removing DOM nodes, this can cause the browser to re-run CPU expensive processes like reflows and repaints.

Instead you can use document fragments, to create a document object that’s separate from the DOM rendered on the page. With a fragment, you can perform DOM operations on it. When you’ve finished doing all you need to, you can append it to the rendered DOM, therefore massively reducing the number of reflow operations.

I use document fragments in my recent <masonry-layout> component.

Imagine that you have a single-page application. You have a <main> element that your JavaScript uses to create and append markup to. If you’re rendering a heavy application, you might need to perform a lot of operations on that DOM element.

Instead of performing those CRUD operations on the DOM itself, you can create a fragment, run the operations on the fragment, and then append it to the document when you’re all done.

Here’s a very stripped back example of me using this in action:

const mainEl = document.querySelector('main');
const docFrag = document.createDocumentFragment();

const div = document.createElement('div');
// perform a bunch of operations on the element, like adding more DOM nodes
docFrag.appendChild(div);

// Add the fragment to the document
mainEl.replaceChildren(docFrag);

Instead of the browser recalculating the page layout and styles on every operation, it does it just when the document is appended to the main element.



If you enjoyed this article, then I figure you like to be kept in the loop with web development tips. If so, the Component Odyssey newsletter might be right up your alley.