← Back toFront-end Tips

Use DocumentFragments when adding a big list of elements

Written byPhuoc Nguyen
Created
28 Apr, 2021
Category
Practice
Tags
DOM, JavaScript
We often use the `appendChild` method to add a new element to a given element:
const li = document.createElement('li');
li.innerHTML = 'List item';

// Append to given list
ul.appendChild(li);
When a new element is inserted to the page, the browser has to recompute the dimensions of its parent and the parent's child nodes. The process is known as the reflow. Similarly, changing the styles of the element might cause a repaint.
Adding a big list of elements to the document might affect the performance of page because it triggers reflow multiple times:
for (let i = 0; i < 100; i++) {
const li = document.createElement('li');
li.innerHTML = `List item ${i}`;
ul.appendChild(li);
}
Depsite the fact that modern browsers make a lot of optimizations including batch updates, it's recommended to use `DocumentFragment` in this case. We create a minimal document without parent, and append our elements to it. It doesn't trigger any reflow or repaint because the document fragment hasn't been added to the page yet:
const fragment = document.createDocumentFragment();

for (let i = 0; i < 100; i++) {
const li = document.createElement('li');
li.innerHTML = `List item ${i}`;
fragment.appendChild(li);
}
Finally, the document fragment is inserted to the page:
ul.appendChild(fragment);
The reflow is triggered once!

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.