2.10 Check JavaScript performance

Shipping less is half of it; running less is the other half.

Check for performance problems in your JavaScript files

Bundle size gets the attention, but a small bundle doing expensive work is still a slow page. Runtime cost is felt directly: taps that do nothing, scrolling that stutters, text lagging behind the keyboard.

This is what Interaction to Next Paint measures.

Long tasks

Anything occupying the main thread for more than 50ms delays input — the browser cannot respond to a click while your code runs.

Find them in the Performance panel; long tasks are flagged with a red corner. The fix is to break the work up and yield:

async function processAll(items) {
  for (const [i, item] of items.entries()) {
    process(item);
    // Let the browser handle input every 50 items.
    if (i % 50 === 0) await scheduler.yield();
  }
}

scheduler.yield() is the modern API; setTimeout(0) is the fallback. For heavy non-DOM work, move it to a Web Worker.

Layout thrashing

Reading a geometric property after writing one forces a synchronous layout recalculation. See stylesheet complexity for the pattern and its fix.

Event handlers

scroll, resize, mousemove and input fire constantly. An expensive handler on any of them guarantees jank.

  • Throttle or debounce, depending on whether you need it during or after.
  • Use passive: true on scroll and touch listeners so the browser need not wait to see whether you will call preventDefault().
  • Prefer IntersectionObserver over scroll handlers for visibility — it runs off the main thread.
el.addEventListener("scroll", onScroll, { passive: true });

Measure rather than guess

Runtime performance is where intuition is least reliable. Record the interaction that feels slow in the Performance panel and read the flame chart before changing anything.

On this page