javascript
49 lines · 8 steps
Batching DOM reads and writes to avoid layout thrash
A scheduler groups all DOM measurements before mutations in a single animation frame to prevent forced reflows.
Explained by
highlit
1class DOMBatcher {
2 constructor() {
3 this.reads = [];
4 this.writes = [];
5 this.scheduled = false;
6 }
7
8 read(task) {
9 this.reads.push(task);
10 this.schedule();
11 }
12
13 write(task) {
14 this.writes.push(task);
15 this.schedule();
16 }
17
18 schedule() {
19 if (this.scheduled) return;
20 this.scheduled = true;
21 requestAnimationFrame(() => this.flush());
22 }
23
24 flush() {
25 const reads = this.reads;
26 const writes = this.writes;
27 this.reads = [];
28 this.writes = [];
29 this.scheduled = false;
30
31 const results = reads.map((task) => task());
32 writes.forEach((task, i) => task(results[i]));
33
34 if (this.reads.length || this.writes.length) {
35 this.schedule();
36 }
37 }
38}
39
40export const batcher = new DOMBatcher();
41
42export function equalizeHeights(elements) {
43 batcher.read(() => Math.max(...elements.map((el) => el.offsetHeight)));
44 batcher.write((maxHeight) => {
45 for (const el of elements) {
46 el.style.height = `${maxHeight}px`;
47 }
48 });
49}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Interleaving DOM reads and writes forces the browser to recompute layout repeatedly, so grouping them by phase eliminates that cost.
- 2A scheduled flag ensures many enqueued tasks collapse into a single requestAnimationFrame callback instead of one per call.
- 3Passing read results into write callbacks lets mutations depend on measurements taken safely before any writes happen.
Related explainers
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
javascript
import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; function csvCell(value) {
Streaming a CSV export in a Next.js route
streaming
csv
readablestream
Advanced
9 steps
javascript
class MovingAverage { constructor(windowSize) { if (!Number.isInteger(windowSize) || windowSize <= 0) { throw new RangeError('windowSize must be a positive integer');
A rolling average over a fixed window
circular-buffer
streaming
async-generators
Intermediate
7 steps
javascript
const { Pool } = require('pg'); const pool = new Pool({ connectionString: process.env.DATABASE_URL,
Per-request Postgres connections in Express
connection-pooling
middleware
transactions
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); const db = require('../db');
Building a paginated orders page in Express
pagination
routing
sql-queries
Intermediate
7 steps
javascript
import { Suspense } from 'react'; import { searchProducts } from '@/lib/products'; import SearchInput from './search-input';
Streaming search results in a Next.js Server Component
server-components
suspense
streaming
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/batching-dom-reads-and-writes-to-avoid-layout-thrash-explained-javascript-3081/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.