brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: JavaScript's IntersectionObserver tells you when an element scrolls into view

Javascript
~/tips/tip-javascript-intersectionobserver-lazy

const observer = new IntersectionObserver((entries) => {

Runs code when an element enters the viewport, without listening to every scroll event.

The old way to do something when an element comes into view is a scroll listener that measures positions dozens of times a second. The browser has a cheaper way.

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      entry.target.classList.add("visible");
      observer.unobserve(entry.target);
    }
  }
}, { rootMargin: "200px" });

document.querySelectorAll(".reveal").forEach((el) => observer.observe(el));

The callback gets a list of entries. isIntersecting is true when the element moved into view. After the first time I call unobserve(), because I only care once; MDN says calling it on an element that is not observed just does nothing.

The options: root is the viewport when you leave it out, rootMargin grows or shrinks that area (default 0px on all sides), and threshold says how much of the element must be visible, default 0. A positive rootMargin like the 200 pixels here starts the work just before the element appears, which is nice for loading content.

I’d use it for loading a heavy widget only when someone scrolls down to it, or for counting which sections people actually reach.

Caveats. The callback runs on the main thread, so keep it short. If you set a root, the observed elements must be inside it. And MDN is not fully clear on the edge case where an element only touches the edge of the viewport, so do not build logic that depends on that exact moment. Test it.

Further reading: MDN: Intersection Observer API, MDN: IntersectionObserver.unobserve()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link