JAVASCRIPT
Optimize DOM Updates with Document Fragments
Improve web performance by batching multiple DOM manipulations into a single reflow using Document Fragments, perfect for large lists or tables.
const listContainer = document.getElementById('myList');
const fragment = document.createDocumentFragment();
const itemsToAdd = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
itemsToAdd.forEach(itemText => {
const listItem = document.createElement('li');
listItem.textContent = itemText;
fragment.appendChild(listItem);
});
listContainer.appendChild(fragment); // Only one DOM reflow
// Example HTML structure:
// <ul id="myList">
// <!-- Items will be added here -->
// </ul>
How it works: A `DocumentFragment` is a lightweight, minimal document object that acts as a temporary container for DOM nodes. Instead of appending elements directly to the live DOM in a loop, which can cause multiple costly reflows and repaints, you append them to the fragment. Once all elements are added to the fragment, the entire fragment is appended to the live DOM in a single operation, drastically improving performance for batch updates.