JAVASCRIPT
Batch DOM Updates with Document Fragments
Improve performance when adding multiple elements to the DOM by using a DocumentFragment, reducing reflows and repaints in JavaScript.
<ul id="my-list"></ul>
<script>
const myList = document.getElementById('my-list');
const fragment = document.createDocumentFragment();
const numItems = 1000;
console.time('DOM insertion with DocumentFragment');
for (let i = 0; i < numItems; i++) {
const listItem = document.createElement('li');
listItem.textContent = `List Item ${i + 1}`;
// Append to the fragment, not directly to the DOM
fragment.appendChild(listItem);
}
// Append the entire fragment to the DOM in one go
myList.appendChild(fragment);
console.timeEnd('DOM insertion with DocumentFragment');
console.log(`${numItems} list items added efficiently.`);
</script>
How it works: When adding many elements to the DOM, directly appending each one can lead to multiple browser reflows and repaints, impacting performance. This snippet demonstrates using `DocumentFragment` to batch these updates. Elements are first created and appended to an in-memory `DocumentFragment`. Once all elements are added to the fragment, the entire fragment is appended to the live DOM in a single operation. This significantly reduces the number of DOM manipulations and improves performance, especially with large numbers of elements.