Creating Document Fragments
You'll learn how to batch multiple DOM changes efficiently using DocumentFragment for better performance.
When you need to add several elements to the DOM at once, inserting them one-by-one can be slow and trigger multiple browser reflows. It's like making ten trips to carry groceries from your car instead of using a basket to carry them all at once.
What is a DocumentFragment?
A DocumentFragment is a lightweight container that lives completely off-screen. It holds DOM nodes temporarily without being part of the live DOM tree. This means changes to it don't trigger reflows or repaints until you insert the entire fragment into the document.
Why Use DocumentFragments?
When you append elements individually to the DOM:
const list = document.getElementById('myList');
for (let i = 0; i < 100; i++) {
const item = document.createElement('li');
item.textContent = `Item ${i}`;
list.appendChild(item); // 100 separate insertions!
}
This causes the browser to recalculate layout 100 times.
The Better Way
const list = document.getElementById('myList');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const item = document.createElement('li');
item.textContent = `Item ${i}`;
fragment.appendChild(item); // Build off-screen
}
list.appendChild(fragment); // One insertion!
You create the fragment with document.createDocumentFragment(), build your structure inside it using methods like appendChild, then insert everything at once. The fragment itself disappears—only its children get added to the target element.
Key Takeaway: Use DocumentFragment to assemble multiple DOM elements off-screen and insert them in a single operation, dramatically improving performance when adding multiple elements to the page.