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}`;


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 =;
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'); = 'none'; = '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 =;

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

if (elapsed < duration) {


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 =;
if (now - lastCall > limit) {
lastCall = now;
func.apply(this, args);

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.