JAVASCRIPT

Use Document Fragments for Efficient DOM Updates

Optimize performance when adding multiple elements to the DOM by utilizing Document Fragments, which minimize reflows and repaints for smoother UI updates.

/**
 * Efficiently adds multiple child elements to a parent using a Document Fragment.
 * @param {HTMLElement} parentElement The parent element to which children will be added.
 * @param {Array<HTMLElement>} childElements An array of HTMLElement nodes to append.
 */
function addChildrenWithFragment(parentElement, childElements) {
  if (!parentElement || !Array.isArray(childElements)) {
    console.error('Invalid arguments: parentElement must be an HTMLElement and childElements must be an array.');
    return;
  }

  const fragment = document.createDocumentFragment();

  childElements.forEach(child => {
    if (child instanceof HTMLElement) {
      fragment.appendChild(child);
    } else {
      console.warn('Skipping non-HTMLElement in childElements array:', child);
    }
  });

  parentElement.appendChild(fragment);
}

// Example Usage:
// <ul id="myList"></ul>
const myList = document.getElementById('myList');
const itemsToAdd = [];

for (let i = 1; i <= 1000; i++) {
  const listItem = document.createElement('li');
  listItem.textContent = `List Item ${i}`;
  itemsToAdd.push(listItem);
}

// Without fragment (less efficient for many items):
// itemsToAdd.forEach(item => myList.appendChild(item));

// With fragment (more efficient):
addChildrenWithFragment(myList, itemsToAdd);
How it works: This snippet demonstrates how to use a `DocumentFragment` to improve DOM update performance. When adding many elements to the DOM sequentially, each `appendChild` operation can trigger costly reflows and repaints. By appending all new elements to a `DocumentFragment` first, and then appending the single fragment to the actual DOM, only one reflow/repaint is triggered, leading to significantly smoother and faster UI updates, especially with large lists or tables.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs