Skip to the page

Observers, workers and the platform · core

IntersectionObserver: lazy loading and infinite scroll

IntersectionObserver tells you asynchronously when an element enters or leaves the viewport (or a root), so you can lazy-load images and load the next page when a sentinel at the bottom becomes visible, without scroll listeners.

The notes

What you must know

  • new IntersectionObserver(callback, { root, rootMargin: '200px', threshold: 0 }); observer.observe(el).
  • Callback gets entries with isIntersecting, intersectionRatio, target. It runs off the scroll path, so no layout reads in a scroll handler.
  • Infinite scroll: observe a sentinel after the last item; when it intersects and you are not already loading and there is more data, fetch the next page.
  • Guard against double loads (a loading flag), stop when there are no more pages (unobserve), and handle errors with a retry.
  • Native <img loading='lazy'> covers simple image lazy-loading; disconnect() on unmount.

The red pen

Common traps: mistake → fix

  • Mistake: "use a scroll listener with getBoundingClientRect"

    Fix: it runs on every scroll and forces layout; the observer is async and cheaper.

  • Mistake: "the callback runs once"

    Fix: it runs on every crossing, so guard against duplicate fetches.

Easy to hard

Questions interviewers ask, easy to hard

  1. How would you build infinite scroll?
  2. How do you avoid loading the same page twice?
  3. Scroll listener vs IntersectionObserver?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview