JAVASCRIPT
Optimize Multiple DOM Updates with DocumentFragment
Improve performance when adding many elements to the DOM by using 'DocumentFragment' to batch updates, reducing browser reflows and repaints.
const listContainer = document.getElementById('myListContainer');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const listItem = document.createElement('li');
listItem.textContent = `Item ${i + 1}`;
fragment.appendChild(listItem);
}
listContainer.appendChild(fragment);
How it works: When adding many elements to the DOM, direct manipulation can be slow due to repeated reflows and repaints. This snippet uses a 'DocumentFragment' as a lightweight, non-document container to build all new elements offline. Once complete, the fragment is appended to the actual DOM in a single, efficient operation.