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.
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.
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');listener addedIn 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.