JAVASCRIPT
Optimize DOM Updates with DocumentFragment for Performance
Enhance web performance by batching multiple DOM manipulations into a single reflow using `DocumentFragment`, preventing costly repeated direct DOM interactions.
function appendLargeListOfItems(containerId, itemsArray) {
const container = document.getElementById(containerId);
if (!container) {
console.error(`Container with ID "${containerId}" not found.`);
return;
}
// Create a DocumentFragment
const fragment = document.createDocumentFragment();
itemsArray.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = item;
fragment.appendChild(listItem);
});
// Append the DocumentFragment to the real DOM once
container.appendChild(fragment);
}
// Example Usage:
// Assume an unordered list with id="myList" exists
// <ul id="myList"></ul>
const dataItems = [];
for (let i = 1; i <= 1000; i++) {
dataItems.push(`Item ${i}`);
}
appendLargeListOfItems('myList', dataItems);
How it works: When adding many elements to the DOM, directly appending them one by one can cause multiple reflows and repaints, leading to performance issues. `DocumentFragment` allows you to build a subtree of DOM nodes in memory without affecting the live DOM. Once the fragment is complete, it can be appended to the real DOM in a single operation, triggering only one reflow and significantly improving performance.