Skip to content
jshacks.dev
Browser

Avoid layout reads inside scroll handlers

Avoid forcing layout in a scroll handler by batching reads before writes, or use IntersectionObserver, so scrolling stays smooth on slow phones.

1 min read
Summarize in AI

Reading offsetHeight or getBoundingClientRect right after changing a style makes the browser compute layout on the spot. Doing that inside every scroll event is the classic way to make a page janky.

layout-thrash.jsJavaScript
const items = [...document.querySelectorAll('.item')];

// slow: read, write, read, write forces layout each time
function slow() {
  for (const item of items) {
    const top = item.getBoundingClientRect().top;
    item.style.opacity = top < innerHeight ? 1 : 0;
  }
}

// fast: all reads first, then all writes
function fast() {
  const tops = items.map((item) => item.getBoundingClientRect().top);
  items.forEach((item, i) => {
    item.style.opacity = tops[i] < innerHeight ? 1 : 0;
  });
}

addEventListener('scroll', () => requestAnimationFrame(fast), { passive: true });
console.log('listener added');
Text
listener added

In slow, every write invalidates layout, so the next read has to recalculate it. In fast, the reads share one layout pass and the writes follow without a read in between. Wrapping in requestAnimationFrame also limits the work to once per frame. The list of properties that force layout is in this gist by Paul Irish.

If you only need to know whether elements are in view, an IntersectionObserver removes the scroll handler entirely. Measure the effect in the DevTools Performance panel before and after.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.