JAVASCRIPT
Efficiently Batch DOM Updates with DocumentFragment
Optimize web page performance by batching multiple DOM manipulations into a single reflow using DocumentFragment, significantly reducing browser rendering cycles and improving responsiveness.
function addItemsEfficiently(parentElement, items) {
const fragment = document.createDocumentFragment();
items.forEach(itemText => {
const li = document.createElement('li');
li.textContent = itemText;
fragment.appendChild(li);
});
parentElement.appendChild(fragment);
}
// Example usage:
const ul = document.getElementById('myList'); // Assume a <ul id="myList"> exists
const data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
addItemsEfficiently(ul, data);
/* HTML context:
<ul id="myList"></ul>
*/
How it works: This snippet demonstrates how to efficiently add multiple elements to the DOM using a DocumentFragment. Instead of appending each new list item directly to the live DOM (which triggers costly reflows and repaints for each operation), we first append all new items to an in-memory DocumentFragment. Once all items are added to the fragment, the entire fragment is appended to the parent element in a single DOM operation. This dramatically reduces the number of browser reflows, leading to much better performance for large lists or frequent updates.