Chapter 7 of 12
7.1 High-Performance DOM Manipulation
Direct DOM mutations trigger expensive browser style calculations, layout recalculations (Reflows), and pixel rendering (Repaints). Optimize batch operations using DocumentFragment.
Batch Insertion with DocumentFragmentjavascript
const list = document.querySelector('#item-list');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
// Single reflow insertion!
list.appendChild(fragment);7.2 Event Delegation Pattern
Instead of attaching event listeners to hundreds of child elements, attach a single listener to a parent container using event bubbling.
Event Delegation Examplejavascript
const container = document.querySelector('#button-container');
container.addEventListener('click', (event) => {
const btn = event.target.closest('button');
if (!btn) return; // Clicked outside a button
console.log(`Clicked action: ${btn.dataset.action}`);
});7.3 Modern Observers (IntersectionObserver)
Lazy Loading Images with IntersectionObserverjavascript
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
obs.unobserve(img); // Stop observing once loaded
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));