JAVASCRIPT
Batch DOM Updates Using Document Fragments
Optimize web performance by using Document Fragments to make multiple DOM changes in a single reflow, significantly reducing browser rendering overhead for lists.
function appendItemsWithFragment(parentId, itemsData) {
const parent = document.getElementById(parentId);
if (!parent) {
console.error(`Parent element with ID "${parentId}" not found.`);
return;
}
const fragment = document.createDocumentFragment();
itemsData.forEach(itemText => {
const li = document.createElement('li');
li.textContent = itemText;
fragment.appendChild(li);
});
parent.appendChild(fragment); // Appends all 'li' elements in one go
}
How it works: To boost performance when adding many elements to the DOM, this function uses `document.createDocumentFragment()`. Instead of appending each element individually (which can trigger costly reflows), elements are first added to the lightweight fragment. The entire fragment is then appended to the actual DOM in a single, efficient operation.