JAVASCRIPT
Optimizing DOM Updates with Document Fragments
Improve performance when adding multiple new elements to the DOM by using `DocumentFragment` to batch insertions, reducing reflows and repaints in web applications.
function addMultipleItemsWithFragment(parentElementSelector, itemsArray) {
const parentElement = document.querySelector(parentElementSelector);
if (!parentElement) {
console.error('Parent element for fragment insertion not found:', parentElementSelector);
return;
}
const fragment = document.createDocumentFragment();
itemsArray.forEach(itemText => {
const listItem = document.createElement('li');
listItem.textContent = itemText;
fragment.appendChild(listItem);
});
// Appending the fragment to the DOM triggers only one reflow/repaint
parentElement.appendChild(fragment);
}
// Example Usage:
// Assume an unordered list with id="myUnorderedList" exists
// const newItems = ['Apple', 'Banana', 'Cherry', 'Date'];
// addMultipleItemsWithFragment('#myUnorderedList', newItems);
// To demonstrate the performance benefit, compare with:
// function addMultipleItemsDirectly(parentElementSelector, itemsArray) {
// const parentElement = document.querySelector(parentElementSelector);
// if (!parentElement) return;
// itemsArray.forEach(itemText => {
// const listItem = document.createElement('li');
// listItem.textContent = itemText;
// parentElement.appendChild(listItem); // Each append triggers reflow/repaint
// });
// }
How it works: When adding a large number of elements to the DOM, direct manipulation can be slow because each addition potentially triggers a browser reflow and repaint. A `DocumentFragment` provides a solution by acting as a lightweight, 'off-DOM' container for elements. Elements can be added to the fragment without affecting the live DOM. Once all elements are assembled in the fragment, the fragment itself is appended to the DOM, resulting in only a single reflow/repaint operation, significantly improving performance.