DEV Community

Cover image for How to Add a Large List of Elements to the DOM Efficiently Using DocumentFragments 🧩
Mike Vardy
Mike Vardy

Posted on

How to Add a Large List of Elements to the DOM Efficiently Using DocumentFragments 🧩

Cover Photo by Sunder Muthukumaran on Unsplash

You may have encountered situations where you need to add a large list of elements to a web page dynamically. For example, you may want to display a list of products, comments, search results, or other data that is fetched from an API or a database.

However, adding a large list of elements to the web page can be challenging in terms of performance and user experience. If you directly manipulate the DOM for each element, you may cause unnecessary reflows and repaints, which can slow down the page rendering and make the user interface unresponsive.

Fortunately, there is a better way to handle this problem: using DocumentFragments. DocumentFragments are a special type of node that can hold other nodes without affecting the live DOM. They allow you to create and manipulate a large list of elements in memory, and then append them to the web page in one go. This can significantly improve the performance and user experience of your web application.

In this post, I will explain what DocumentFragments are, how they differ from traditional DOM manipulation, and how to use them to add a large list of elements efficiently. I will also show you some best practices, real-world use cases, performance comparisons, and browser compatibility issues related to DocumentFragments.

Let's get started!


The DocumentFragments API

A DocumentFragment is a node that can contain other nodes, but is not part of the live DOM tree. It acts as a lightweight document that can store a fragment of HTML or XML content.

You can create a DocumentFragment using the document.createDocumentFragment() method. This returns an empty DocumentFragment object that you can populate with other nodes.

Unlike regular nodes, DocumentFragments do not have any parent or sibling nodes. They are isolated from the live DOM and do not trigger any reflows or repaints when you modify them. This means that you can add, remove, or change the nodes inside a DocumentFragment without affecting the web page layout or performance.

When you are ready to insert the nodes from a DocumentFragment into the live DOM, you can use the appendChild() or insertBefore() methods on any node that accepts child nodes. This will move all the nodes from the DocumentFragment to the specified location in the live DOM, and empty the DocumentFragment object.

The advantage of using DocumentFragments is that they allow you to perform batch operations on a large number of nodes in memory, and then append them to the web page in one go. This reduces the number of DOM manipulations and improves the performance and user experience of your web application.


The Problem with Traditional DOM Manipulation

To understand why DocumentFragments are useful, let's first look at what happens when you use traditional DOM manipulation to add a large list of elements to a web page.

Suppose you have an empty <ul> element in your HTML document, and you want to add 1000 <li> elements to it dynamically using JavaScript. One way to do this is to use a loop and create each <li> element using the document.createElement() method. Then, for each <li> element, you can set its text content using the textContent property, and append it to the <ul> element using the appendChild() method.

Here is an example of how this code might look like:

// Get the <ul> element
const ul = document.getElementById("list");

// Simulate adding 1000 list items
for (let i = 0; i < 1000; i++) {
  // Create an <li> element
  const li = document.createElement("li");
  // Set its text content
  li.textContent = "Item " + (i + 1);
  // Append it to the <ul> element
  ul.appendChild(li);
}
Enter fullscreen mode Exit fullscreen mode

This code seems simple and straightforward, but it has some serious drawbacks in terms of performance and user experience.

First of all, every time you append an <li> element to the <ul> element, you are modifying the live DOM tree. This means that the browser has to recalculate the layout and style of the web page, and repaint the affected regions on the screen. These operations are expensive and time-consuming, especially when you have a large number of complex elements.

Secondly, every time you modify the live DOM tree, you are blocking the main thread of JavaScript execution. This means that while the loop is running, no other JavaScript code can run, and no user interactions can be processed. This can make the web page unresponsive and freeze the user interface until all the elements are added.

As a result, using traditional DOM manipulation for adding a large list of elements can cause poor performance and user experience issues such as:

  • Slow page rendering
  • Janky animations
  • Delayed user feedback
  • High CPU and memory usage
  • Battery drain

Creating and Using DocumentFragments

To avoid the problems of traditional DOM manipulation, you can use DocumentFragments to add a large list of elements efficiently.

The idea is to create a DocumentFragment object, and populate it with the <li> elements in memory. Then, you can append the DocumentFragment object to the <ul> element in one go. This way, you only modify the live DOM once, and avoid unnecessary reflows and repaints.

Here is an example of how to use DocumentFragments to add 1000 <li> elements to a web page:

// Create a DocumentFragment
const fragment = document.createDocumentFragment();

// Simulate adding 1000 list items to the DocumentFragment
for (let i = 1; i <= 1000; i++) {
  const li = document.createElement("li");
  li.textContent = `List Item ${i}`;
  fragment.appendChild(li);
}

// Now, append the entire DocumentFragment to the live DOM
const myList = document.getElementById("myList");
myList.appendChild(fragment);
Enter fullscreen mode Exit fullscreen mode

With DocumentFragments, you perform a single DOM modification operation rather than 1000 individual ones. This optimization significantly reduces the overhead associated with layout calculations and repaints, resulting in a faster and smoother user experience.

Unlike the first example, using DocumentFragments doesn't block the main JavaScript thread. It means your web page remains responsive and doesn't freeze during the process, ensuring a better user experience.

By minimizing layout recalculations and repaints, your web application consumes fewer resources. This leads to lower CPU and memory usage, extending the life of mobile device batteries and providing a more energy-efficient experience.


In conclusion, DocumentFragments are a powerful tool in a web developer's toolkit. They enable you to efficiently add large lists of elements to a web page, improving performance and user experience. By batching DOM modifications and reducing rendering bottlenecks, you can create web applications that are both faster and more responsive.

So, the next time you're faced with adding a significant number of elements dynamically, remember DocumentFragments. They're the secret to a more efficient and user-friendly web.

Happy coding! 🚀✨

Top comments (0)