JAVASCRIPT
Optimize Bulk DOM Updates with DocumentFragment
Improve web application performance by using `DocumentFragment` to efficiently add multiple elements to the DOM, minimizing costly reflows and repaints.
const fragment = document.createDocumentFragment();
const listContainer = document.getElementById('myListContainer');
// Create multiple list items and append them to the fragment
for (let i = 0; i < 5; i++) {
const listItem = document.createElement('li');
listItem.textContent = `List Item ${i + 1}`;
fragment.appendChild(listItem);
}
// Append the DocumentFragment to the DOM in a single operation
listContainer.appendChild(fragment);
// Example of adding another single element directly
const newHeader = document.createElement('h3');
newHeader.textContent = 'Items Loaded!';
listContainer.prepend(newHeader); // Inserts at the beginning of the listContainer
How it works: `DocumentFragment` is a lightweight, minimal document object that serves as a temporary container for DOM nodes. When you append a `DocumentFragment` to an element in the actual DOM, only its children are moved, not the fragment itself. This approach significantly boosts performance for bulk DOM manipulations, as it triggers only one reflow and repaint operation when the fragment is finally attached, rather than one for each individual child element.