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:js
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:
js
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:js
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:
js
ul.appendChild(fragment);
The reflow is triggered once!
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
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.
Phước Nguyễn