DOM Reflow, Repaint & Rendering Pipeline
Published by Brayan K
Modern web performance starts with understanding how the browser actually turns your HTML, CSS, and JavaScript into pixels on the screen. This lesson reveals the rendering pipeline, reflow/repaint costs, and professional optimization techniques used by Meta, Google, Netflix, and Airbnb.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Measure real geometry without pretending to count the rendering engine
Run these examples in Web page mode: they create real elements inside the editor preview. DOM changes, style calculation, layout, painting and compositing are different kinds of work. Their costs depend on the affected tree, styles, browser and device. A JavaScript write counter is not a count of layouts, paints or frames.
const box = document.createElement("div");
box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0";
document.getElementById("app").append(box);
console.log(box.offsetWidth); // Integer layout width, including this border box.
box.style.width = "140px"; // Change the requested width.
console.log(box.offsetWidth); // Ask the browser for the current layout width.
console.log(box.style.width); // Read the inline declaration, a different kind of value.
// ✅ Expected output:
// 100
// 140
// 140pxThe outputs establish geometry, not how long the browser took or how many internal layout passes it performed. A geometry query after an invalidating change can require pending style/layout work to become current. DOM Manipulation owns creating and selecting nodes, and Performance Optimization owns establishing a measured performance problem.
A DOM tree is not the same thing as visible boxes
const item = document.createElement("div");
item.style.cssText = "box-sizing:border-box;width:120px;height:20px;padding:0;border:0";
console.log(item.isConnected, item.offsetWidth);
document.getElementById("app").append(item);
console.log(item.isConnected, item.offsetWidth);
// ✅ Expected output:
// false 0
// true 120const box = document.createElement("div");
box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0";
document.getElementById("app").append(box);
box.style.visibility = "hidden";
console.log(box.offsetWidth);
box.style.display = "none";
console.log(box.offsetWidth);
box.style.display = "block";
console.log(box.offsetWidth, box.style.visibility);
// ✅ Expected output:
// 100
// 0
// 100 hiddenvisibility:hidden retains the layout box here; display:none removes it from layout. Neither offsetWidth result tells you whether an element is perceivable or accessible in every possible state. Content, fonts, ancestor layout and style rules can also change geometry without an explicit width assignment.
Choose the measurement that answers your question
const item = document.createElement("div");
item.style.cssText = "box-sizing:content-box;width:100px;height:20px;padding:5px;border:2px solid;margin:0";
document.getElementById("app").append(item);
console.log(item.style.width, item.clientWidth, item.offsetWidth);
item.style.boxSizing = "border-box";
console.log(item.style.width, item.clientWidth, item.offsetWidth);
// ✅ Expected output:
// 100px 110 114
// 100px 96 100const box = document.createElement("div");
box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0";
document.getElementById("app").append(box);
box.style.transformOrigin = "left top";
box.style.transform = "scaleX(2)";
console.log(box.offsetWidth, box.getBoundingClientRect().width);
box.style.transform = "none";
console.log(box.offsetWidth, box.getBoundingClientRect().width);
// ✅ Expected output:
// 100 200
// 100 100offsetWidth is an integer layout measurement; getBoundingClientRect describes the viewport-relative visual bounding rectangle and includes transforms. This fixed example avoids fractions and scrolling. It does not establish that every transform is free, always GPU-accelerated or guaranteed to avoid paint. Layer promotion and raster work depend on the actual scene.
const box = document.createElement("div");
box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0";
document.getElementById("app").append(box);
const before = box.offsetWidth;
box.style.backgroundColor = "rgb(20, 40, 60)";
console.log(before === box.offsetWidth);
console.log(getComputedStyle(box).backgroundColor);
// ✅ Expected output:
// true
// rgb(20, 40, 60)The stable width and computed colour are the observations. They do not certify that the browser painted exactly once or used a particular layer. Paint concerns visual appearance; layout concerns geometry. Compositing combines rendered layers, and not every element necessarily has its own composited layer.
Separate a read phase from a write phase when the calculation allows it
const root = document.getElementById("app");
const boxes = [80, 100, 120].map(width => {
const item = document.createElement("div");
item.style.cssText = "box-sizing:border-box;height:10px;padding:0;border:0;width:" + width + "px";
root.append(item); return item;
});
const operations = [];
for (const item of boxes) {
operations.push("read"); const width = item.offsetWidth;
operations.push("write"); item.style.width = width + 10 + "px";
}
console.log(operations.join(","));
console.log(boxes.map(item => item.offsetWidth).join(","));
// ✅ Expected output:
// read,write,read,write,read,write
// 90,110,130const root = document.getElementById("app");
const boxes = [80, 100, 120].map(width => {
const item = document.createElement("div");
item.style.cssText = "box-sizing:border-box;height:10px;padding:0;border:0;width:" + width + "px";
root.append(item); return item;
});
const operations = [];
const widths = boxes.map(item => { operations.push("read"); return item.offsetWidth; });
boxes.forEach((item, index) => {
operations.push("write"); item.style.width = widths[index] + 10 + "px";
});
console.log(operations.join(","));
console.log(boxes.map(item => item.offsetWidth).join(","));
// ✅ Expected output:
// read,read,read,write,write,write
// 90,110,130Both examples implement the same independent old-width calculation. The trace counts our API operations, not engine reflows. Grouping reads removes this loop’s repeated read-after-write pattern; the first read may still require layout. If a later measurement intentionally depends on an earlier write, blindly moving all reads changes the algorithm. Profile before choosing a different dependency structure.
A fragment groups DOM construction; it does not promise one layout
const root = document.getElementById("app");
const fragment = document.createDocumentFragment();
const first = document.createElement("p"); first.textContent = "A";
const second = document.createElement("p"); second.textContent = "B";
fragment.append(first, second);
console.log(fragment.childNodes.length, first.isConnected);
root.append(fragment);
console.log(fragment.childNodes.length, root.children.length, first.isConnected);
console.log(root.firstElementChild === first);
// ✅ Expected output:
// 2 false
// 0 2 true
// trueThis is useful for assembling nodes and keeping construction code clear. It neither clones the children nor guarantees a speed improvement or one reflow. Repeated connected writes without intervening geometry reads may already be batched by the browser. Compare the actual workload instead of labelling every append a reflow.
A frame callback is an opportunity to coordinate work, not proof of a paint
const trace = [];
const finished = new Promise(resolve => {
window.requestAnimationFrame(() => { trace.push("frame callback"); resolve(); });
});
trace.push("sync");
await Promise.resolve();
trace.push("microtask continuation");
await finished;
console.log(trace.join(","));
// ✅ Expected output:
// sync,microtask continuation,frame callbackThe callback is requested once; animation requires another request. Browsers commonly pause these callbacks in background tabs, and display rates differ. A callback runs before a rendering opportunity’s repaint, but a resolved callback promise does not prove the pixels were presented to a user. Do not put a long computation into requestAnimationFrame and expect the scheduling API to make it cheap.
const box = document.createElement("div");
box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0";
document.getElementById("app").append(box);
box.style.width = "110px";
await Promise.resolve();
box.style.width = "130px";
console.log(box.offsetWidth);
// ✅ Expected output:
// 130We can check the final width. This program provides no observation of an intermediate paint. Event Loop, Microtasks & Async Internals owns tasks and microtasks, while Debouncing & Throttling for Performance owns policies that retain or drop frequent calls.
Use a performance recording to test the hypothesis
In Chrome DevTools, record one reproducible interaction in the Performance panel. Inspect main-thread tasks, style/layout work and the call stacks around forced layout. Compare the same content, viewport and interaction after a change, and keep functional behaviour constant. Distinguish scripting, layout, paint and compositing rather than reporting one undifferentiated DOM-operation number.
The runnable examples below establish order and geometry. They do not provide portable millisecond budgets, frame-rate guarantees, universal “most expensive” rankings or evidence about any named company’s implementation. Large trees, costly selectors, image/font changes and long JavaScript tasks need their own measurements. Use will-change sparingly after profiling: keeping extra layers can consume resources.
Guided exercise: read once per item, then write
Fill each literal hint. The goal is to use old border-box widths and add five pixels without interleaving the two phases.
const root = document.getElementById("app");
const boxes = [40, 60].map(width => {
const item = document.createElement("div");
item.style.cssText = "box-sizing:border-box;width:" + width + "px;height:10px;padding:0;border:0";
root.append(item); return item;
});
const widths = boxes.___(item => item.offsetWidth); // 👉 replace ___ with map
boxes.forEach((item, index) => {
item.style.width = widths[___] + 5 + "px"; // 👉 replace ___ with index
});
console.log(boxes.map(item => item.___).join(",")); // 👉 replace ___ with offsetWidth
// ✅ Expected output:
// 45,65Independent brief: batch paired measurements and writes
Write createFrameBatcher(request, cancel, onError). Each add(read, write) queues a job whose read result becomes its write argument. Request one callback for pending work, take a snapshot when it begins, run all snapshot reads first, then each successful read’s write. A read failure skips only that job’s write; report synchronous failures through a trusted non-throwing onError and continue.
Jobs added during either phase belong to a later callback. Dispose cancels queued work, releases queued references, rejects later adds and stops remaining jobs if called during a flush. It cannot undo an already-run write. Handles may be zero; callbacks are synchronous; reads must avoid writes and writes must avoid geometry reads for the intended batching discipline. Check order, failure identity, reentrant additions, cancellation and actual DOM widths.
function createFrames() {
let nextId = 0;
const pending = new Map();
return {
request(callback) { const id = nextId++; pending.set(id, callback); return id; },
cancel(id) { pending.delete(id); },
step() {
const batch = [...pending]; pending.clear();
for (const [, callback] of batch) callback();
},
pending: () => pending.size
};
}
function createFrameBatcher(request, cancel, onError) {
let queued = [], handle = null, closed = false;
function flush() {
handle = null;
const batch = queued; queued = [];
const ready = [];
for (const job of batch) {
if (closed) break;
try { ready.push({ write: job.write, value: job.read() }); }
catch (error) { onError(error); }
}
for (const job of ready) {
if (closed) break;
try { job.write(job.value); }
catch (error) { onError(error); }
}
}
return {
add(read, write) {
if (closed) throw new Error("batcher is closed");
if (typeof read !== "function" || typeof write !== "function") throw new TypeError("read and write must be functions");
queued.push({ read, write });
if (handle === null) handle = request(flush);
},
dispose() {
if (closed) return;
closed = true;
if (handle !== null) cancel(handle);
handle = null; queued = [];
}
};
}
const frames = createFrames();
const trace = [], errors = [];
const batch = createFrameBatcher(frames.request, frames.cancel, error => errors.push(error));
const root = document.getElementById("app");
const boxes = [50, 70].map(width => {
const item = document.createElement("div");
item.style.cssText = "box-sizing:border-box;width:" + width + "px;height:10px;padding:0;border:0";
root.append(item); return item;
});
boxes.forEach((item, index) => batch.add(
() => { trace.push("read" + index); return item.offsetWidth; },
width => { trace.push("write" + index); item.style.width = width + 5 + "px"; }
));
console.log(frames.pending());
frames.step();
console.log(trace.join(","), boxes.map(item => item.offsetWidth).join(","));
const failure = { code: "measurement failed" };
batch.add(() => { throw failure; }, () => trace.push("must not write"));
batch.add(() => 8, value => console.log("survivor", value));
frames.step();
console.log(errors.length, errors[0] === failure);
batch.add(() => {
batch.add(() => "later", value => console.log(value));
return "current";
}, value => console.log(value));
frames.step();
console.log(frames.pending());
frames.step();
batch.add(() => "cancelled", value => console.log(value));
batch.dispose(); batch.dispose(); frames.step();
console.log(frames.pending());
try { batch.add(() => 1, () => {}); } catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// 1
// read0,read1,write0,write1 55,75
// survivor 8
// 1 true
// current
// 1
// later
// 0
// Error batcher is closedReference notes
Google’s layout-thrashing guidance explains forced layout and read/write batching. MDN documents DocumentFragment and requestAnimationFrame. The browser, not a hand-written reflow simulator, produces every geometry output here.
Practice quiz
What does this complete program print? const box=document.createElement("div");box.style.cssText="box-sizing:border-box;width:90px;height:10px;padding:0;border:0";console.log(box.offsetWidth);document.getElementById("app").append(box);console.log(box.offsetWidth);
- 0 90
- 90 90
- 0 0
- 90 0
Answer: 0 90. The detached box has no rendered geometry; insertion gives it its specified border-box width.
What does this complete program print? const box = document.createElement("div"); box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0"; document.getElementById("app").append(box); box.style.visibility="hidden";console.log(box.offsetWidth);box.style.display="none";console.log(box.offsetWidth);
- 0 0
- 100 0
- 100 100
- 0 100
Answer: 100 0. Visibility preserves this layout box while display none removes it.
What does this complete program print? const box = document.createElement("div"); box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0"; document.getElementById("app").append(box); box.style.transform="scaleX(2)";console.log(box.offsetWidth,box.getBoundingClientRect().width);
- 200 200
- 100 100
- 100 200
- 200 100
Answer: 100 200. Transform affects the visual rectangle but not offsetWidth.
What does this complete program print? const fragment=document.createDocumentFragment();const item=document.createElement("p");fragment.append(item);document.getElementById("app").append(fragment);console.log(fragment.childNodes.length,item.isConnected);
- 1 true
- 0 false
- 1 false
- 0 true
Answer: 0 true. Fragment insertion moves its children into the connected parent.
What does this complete program print? const trace=[];const values=[1,2].map(n=>{trace.push("read");return n});values.forEach(()=>trace.push("write"));console.log(trace.join(","));
- read,read,write,write
- read,write,read,write
- write,write,read,read
- read,write
Answer: read,read,write,write. The map phase finishes before the forEach phase starts.
What does this complete program print? const box = document.createElement("div"); box.style.cssText = "box-sizing:border-box;width:100px;height:20px;margin:0;padding:0;border:0"; document.getElementById("app").append(box); box.style.width="125px";console.log(box.style.width,box.offsetWidth);
- 125 125px
- 125px 125
- 100px 125
- 125px 100
Answer: 125px 125. The inline declaration is a string while offsetWidth is a numeric layout measurement.
What does this complete program print? const item=document.createElement("div");item.style.cssText="box-sizing:content-box;width:100px;padding:5px;border:2px solid";document.getElementById("app").append(item);console.log(item.clientWidth,item.offsetWidth);
- 100 100
- 100 110
- 110 114
- 114 110
Answer: 110 114. Client width includes padding; offset width also includes borders.
What does this complete program print? const jobs=new Map([[0,()=>{}]]);let handle=0;if(handle!==null)jobs.delete(handle);handle=null;console.log(jobs.size,handle===null);
- 1 true
- 0 false
- 1 false
- 0 true
Answer: 0 true. A null sentinel permits cancellation of a valid zero handle.
Continue this course
- Previous: Debouncing & Throttling for Performance
- Next: Virtual DOM Concepts & Efficient UI Updates — How frameworks like React use a virtual DOM to minimise real DOM changes
- Quick reference: JavaScript cheat sheet