Course contentsShow
← Web Development
Lesson 2063 of 2,98238. JavaScript Performance in the BrowserFree lesson

Batch DOM Reads and Writes

Pattern for grouping all DOM measurements before any modifications to avoid forced reflows.

Batch DOM Reads and Writes

You'll learn how to group all DOM measurements before any modifications to avoid forced reflows and dramatically improve performance.

The Core Problem

When you interleave DOM reads (like measuring element dimensions) with DOM writes (like changing styles), you force the browser to stop and recalculate the layout every single time. This is layout thrashing—a concept you just learned about.

Think of it like repeatedly asking someone to measure a room, then moving furniture, then measuring again, then moving more furniture. Instead, you should measure everything first, write down all your measurements, then rearrange all the furniture at once.

The Batching Pattern

The solution is simple but requires discipline: separate your reads from your writes.

Bad (interleaved reads/writes):

// Read, write, read, write = multiple forced reflows!
const height1 = element1.offsetHeight;
element1.style.height = height1 + 10 + 'px';

const height2 = element2.offsetHeight;
element2.style.height = height2 + 10 + 'px';

Good (batched):

// All reads first
const height1 = element1.offsetHeight;
const height2 = element2.offsetHeight;

// Then all writes
element1.style.height = height1 + 10 + 'px';
element2.style.height = height2 + 10 + 'px';

By reading all measurements before making any changes, the browser only needs to recalculate layout once after all your writes are complete, instead of after each individual write.

Why It Works

The browser is smart: it batches layout calculations when it can. But when you read a layout property after a write, you force it to calculate immediately (forced synchronous layout) to give you accurate data. Batching lets the browser work on its own schedule.

Key Takeaway: Always batch your DOM reads together and separate them from DOM writes to avoid forcing the browser into expensive, repeated layout recalculations—this single pattern can eliminate layout thrashing entirely.