JAVASCRIPT
Batch DOM Updates with DocumentFragment
Learn to use 'DocumentFragment' to group multiple DOM operations and append them to the live DOM in a single step, minimizing reflows and improving performance.
const fragment = document.createDocumentFragment();
const data = ['Item A', 'Item B', 'Item C', 'Item D'];
data.forEach(itemText => {
const li = document.createElement('li');
li.textContent = itemText;
fragment.appendChild(li);
});
const targetUl = document.getElementById('targetUl');
if (targetUl) {
targetUl.appendChild(fragment);
}
How it works: This code demonstrates the use of 'DocumentFragment' for efficient DOM manipulation. Instead of appending each new 'li' element directly to the live DOM, they are first added to an in-memory 'DocumentFragment'. Once all elements are prepared within the fragment, the entire fragment is appended to the 'targetUl' in a single operation, significantly reducing browser reflows and repaints, thus improving performance.