Skip to main content

Using Document Fragments in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use Document Fragments in JavaScript DOM to optimize the performance of your web applications by minimizing DOM reflows and repaints.

What are Document Fragments?

Document Fragments are lightweight, memory-efficient containers that can hold multiple elements without being part of the main DOM tree. They are useful for optimizing performance when performing batch updates, such as adding or removing multiple elements at once. When elements are inserted or removed from a Document Fragment, they do not trigger reflows or repaints, which can be expensive in terms of performance.

Example: Creating a Document Fragment

Let's consider the following HTML structure:

<ul id="list">
<!-- List items will be added here -->
</ul>

Now, we'll use a Document Fragment to add multiple list items to the list:

const list = document.getElementById('list');

const fragment = document.createDocumentFragment();

for (let i = 1; i <= 5; i++) {
const listItem = document.createElement('li');
listItem.textContent = `Item ${i}`;
fragment.appendChild(listItem);
}

list.appendChild(fragment);

After executing this code, the updated HTML structure will be:

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

In this example, we used a Document Fragment to create and store multiple list items before appending them to the list. By doing so, we only trigger a single reflow and repaint when the fragment is appended to the list, improving the performance of our web application.

Live Playground, Try it Yourself

Conclusion

In this tutorial, we have learned how to use Document Fragments in JavaScript DOM to optimize the performance of your web applications. By using Document Fragments to perform batch updates on the DOM, you can minimize the number of reflows and repaints, leading to faster and more responsive web applications.