JAVASCRIPT

Optimize Multiple DOM Updates with DocumentFragment

Improve performance when adding many elements to the DOM by using 'DocumentFragment' to batch updates, reducing browser reflows and repaints.

const listContainer = document.getElementById('myListContainer');
const fragment = document.createDocumentFragment();

for (let i = 0; i < 100; i++) {
  const listItem = document.createElement('li');
  listItem.textContent = `Item ${i + 1}`;
  fragment.appendChild(listItem);
}

listContainer.appendChild(fragment);
How it works: When adding many elements to the DOM, direct manipulation can be slow due to repeated reflows and repaints. This snippet uses a 'DocumentFragment' as a lightweight, non-document container to build all new elements offline. Once complete, the fragment is appended to the actual DOM in a single, efficient operation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs