JAVASCRIPT
Optimize Batch DOM Appends with DocumentFragment
Improve performance of adding many elements to the DOM by using DocumentFragment to minimize reflows and repaints with a single DOM insertion.
function appendManyElementsEfficiently(parentId, items) {
const parent = document.getElementById(parentId);
if (!parent) {
console.error('Parent element not found:', parentId);
return;
}
const fragment = document.createDocumentFragment();
items.forEach(itemText => {
const listItem = document.createElement('li');
listItem.textContent = itemText;
fragment.appendChild(listItem);
});
parent.appendChild(fragment); // Append the fragment to the DOM once
console.log(`Appended ${items.length} items to '${parentId}' efficiently.`);
}
// Example Usage:
// HTML: <ul id="efficientList"></ul>
const largeDataSet = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
appendManyElementsEfficiently('efficientList', largeDataSet);
How it works: When appending many elements to the DOM consecutively, direct manipulation can cause multiple reflows and repaints, leading to performance issues. This snippet introduces `DocumentFragment`, a lightweight container that allows you to build a subtree of DOM nodes off-screen. All child nodes are appended to the fragment first, and then the fragment itself is appended to the actual DOM. This results in only one single reflow and repaint operation, significantly improving performance for batch DOM updates.