JAVASCRIPT
Efficiently Append Multiple DOM Elements Using DocumentFragment
Improve performance when adding many elements to the DOM by using a DocumentFragment, which minimizes costly browser reflows and repaints for better user experience.
const parent = document.getElementById('container');
const fragment = document.createDocumentFragment();
const items = ['Item A', 'Item B', 'Item C', 'Item D', 'Item E'];
items.forEach(text => {
const li = document.createElement('li');
li.textContent = text;
fragment.appendChild(li);
});
parent.appendChild(fragment); // Only one DOM operation to append all items
// Example HTML for context:
// <ul id="container"></ul>
How it works: This snippet demonstrates how to efficiently add multiple elements to the DOM using a `DocumentFragment`. Instead of appending each new `<li>` directly to the `parent` (which would trigger multiple expensive reflows/repaints for each addition), elements are first added to the lightweight `DocumentFragment`. Once all desired elements are built within the fragment, the entire fragment is appended to the `parent` in a single DOM operation, significantly improving rendering performance, especially for large lists.