24. Mini project: finding and fixing jank with the Performance panel
A step-by-step diagnostic workflow (Chrome DevTools, but Firefox's Performance panel is functionally equivalent):
- Open DevTools → Performance tab → click Record → interact with the janky part of the page → Stop.
- Look at the frame chart: red triangles mark dropped frames.
- Click a slow frame and read the bottom-up/call tree: is time going to "Scripting" (your JS), "Rendering" (layout/style), or "Painting"?
- If "Rendering" dominates and shows repeated "Layout" entries inside a
single frame — that's layout thrashing (§21's bad example):
alternating reads (
getComputedStyle,.offsetHeight) and writes (.style.x = ...) in a loop, each read forcing the browser to flush pending layout work synchronously to answer accurately. - Fix: batch all reads first, then all writes:
// BAD: read, write, read, write — forces N synchronous layouts for N elements
elements.forEach(el => {
const h = el.offsetHeight; // READ (forces layout flush if dirty)
el.style.height = h * 2 + "px"; // WRITE (invalidates layout)
});
// GOOD: all reads, then all writes — ONE layout flush total
const heights = elements.map(el => el.offsetHeight); // all READs
elements.forEach((el, i) => { el.style.height = heights[i] * 2 + "px"; }); // all WRITEs