Skip to main content

Performance Optimization

In this tutorial, we'll discuss various techniques to optimize your DOM manipulation code for better performance.

1. Minimize DOM manipulation

Minimizing the number of DOM operations can significantly improve performance. Use techniques like Document Fragments, Virtual DOM, or batching updates to minimize the number of times the browser needs to update the DOM.

// Example: Using Document Fragment to minimize DOM updates
const list = document.querySelector('#myList');
const fragment = document.createDocumentFragment();

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

list.appendChild(fragment);

2. Efficient event handling

Optimize event handling by using event delegation and removing unused event listeners.

// Example: Using event delegation for better performance
const list = document.querySelector('#myList');

list.addEventListener('click', event => {
const target = event.target;
if (target.tagName === 'LI') {
console.log('List item clicked:', target.textContent);
}
});

3. Reduce CSS reflow and repaint

Minimize the number of reflow and repaint operations by batching style changes or using the requestAnimationFrame method.

// Example: Batch style changes to minimize reflow
const elem1 = document.querySelector('#elem1');
const elem2 = document.querySelector('#elem2');

elem1.style.display = 'none';
elem2.style.display = 'none';

4. Use requestAnimationFrame

Use requestAnimationFrame for animations and DOM updates that need to be synchronized with the browser's rendering.

// Example: Using requestAnimationFrame for smooth animation
function animate(element, duration) {
const start = performance.now();

function update(time) {
const elapsed = time - start;
element.style.transform = `translateX(${(elapsed / duration) * 100}px)`;

if (elapsed < duration) {
requestAnimationFrame(update);
}
}

requestAnimationFrame(update);
}

const element = document.querySelector('#animatedElement');
animate(element, 2000);

5. Debounce and throttle events

Debounce or throttle events that fire frequently, like scroll or resize events, to improve performance.

// Example: Throttling a scroll event
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall > limit) {
lastCall = now;
func.apply(this, args);
}
};
}

window.addEventListener(
'scroll',
throttle(() => {
console.log('Scroll event fired');
}, 200)
);

By using these techniques, you can optimize your DOM manipulation code and improve the overall performance of your application.