← Back to all snippets
JAVASCRIPT

Optimize DOM Updates with DocumentFragment

Enhance performance when adding multiple elements to the DOM by using `DocumentFragment` to minimize reflows and repaints, improving user experience.

<ul id="list-container" style="border: 1px solid #b2ebf2; padding: 10px; margin-top: 10px;"></ul>

<script>
const fragment = document.createDocumentFragment();
const container = document.getElementById('list-container');

const numberOfItems = 100;
console.time('DOM_Append_Fragment');

for (let i = 0; i < numberOfItems; i++) {
  const listItem = document.createElement('li');
  listItem.textContent = `List Item ${i + 1}`;
  listItem.style.padding = '2px 0';
  fragment.appendChild(listItem);
}

container.appendChild(fragment);
console.timeEnd('DOM_Append_Fragment');
console.log(`Added ${numberOfItems} items efficiently.`);
</script>
How it works: When a large number of elements need to be added to the DOM, appending them one by one can be inefficient due to multiple browser reflows and repaints. `DocumentFragment` provides a solution by acting as a lightweight, in-memory container for DOM nodes. Elements are first created and appended to this fragment. Once all elements are collected within the fragment, the entire fragment is appended to the actual DOM in a single operation. This significantly reduces the number of direct DOM manipulations, leading to better performance and a smoother user experience, as demonstrated by the `console.time` measurement.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs