Performance
Runtime Performance
Runtime performance is how smoothly your page behaves after loading — scrolling, animations, and responding to input. The goal is a steady 60 frames per second (about 16ms per frame).
Reflow vs repaint
When the DOM or styles change, the browser does work:
- Reflow (layout) — recalculates element positions and sizes. Expensive; can cascade to the whole page. Triggered by changing
width,height,top, adding elements, or reading layout properties. - Repaint — redraws pixels without changing layout (e.g.,
color). Cheaper.
Animate cheaply with transform and opacity
transform and opacity are handled by the GPU compositor — they skip layout and paint entirely, staying smooth even under load.
/* ✅ Smooth — GPU-accelerated */
.box { transition: transform 0.3s; }
.box:hover { transform: translateX(20px); }
/* ❌ Janky — triggers layout every frame */
.box { transition: left 0.3s; }
.box:hover { left: 20px; }
💡
Rule: for movement use transform: translate(), not top/left. For fades use opacity, not visibility/display.
Avoid layout thrashing
Reading a layout property right after writing styles forces a synchronous reflow. In a loop, this is catastrophic:
// ❌ Thrashing — read after write, every iteration
items.forEach((el) => {
el.style.width = el.offsetWidth + 10 + "px";
});
// ✅ Batch: read all first, then write all
const widths = items.map((el) => el.offsetWidth);
items.forEach((el, i) => {
el.style.width = widths[i] + 10 + "px";
});
Debounce and throttle expensive handlers
Rapid events (scroll, resize, input) can fire hundreds of times per second. Limit how often your handler runs:
- Debounce — run once after activity stops (e.g., search-as-you-type).
- Throttle — run at most once per interval (e.g., scroll tracking).
Offload heavy work
- Use Web Workers to run CPU-intensive computation off the main thread so the UI stays responsive.
- Use
requestAnimationFramefor JavaScript animations (synced to the display refresh). - Use
content-visibility: autoto skip rendering off-screen content on long pages.
Watch & Learn
A recommended video to watch alongside this chapter.
More “Runtime Performance” videos on YouTube