Intersection Observer API Explained, with Examples
threshold, rootMargin and intersectionRatio, then lazy images, infinite-scroll sentinels, pausing videos, scroll-spy and ad viewability.
Related chapters
- Core Web Vitals in Production: LCP, INP and CLS
- The Cost of JavaScript: Bundle Size, Parsing and Hydration
- Critical Rendering Path Explained: DOM, CSSOM, Paint
- Critical CSS: Inline Above-the-Fold Styles
- CSS Performance: Selectors, @import and Layout Cost
- HTTP Caching Explained: Cache-Control, ETag, CDN
- Lazy Loading Images and Code: Best Practices
- List Virtualization (Windowing) in React Explained
- How Mobile Browsers Work: Camera, Permissions, Quirks
- Frontend Performance Case Studies: Netflix, Airbnb, Flipkart
Keep learning
Overview
Ad slot Chapter 67 · intersection observer The browser tells you when a box crosses a line You name a root, a margin, and a threshold. A callback runs when the overlap crosses that threshold.
3. What you decide in production
When the callback runs One frame: style and layout, then the intersection check, then paint. Your callback runs later as its own task. your task compositor, not blocked The task is still the main thread A light callback fits between frames. A callback that mounts two hundred nodes runs past the next frame deadline and drops it. mount 200 nodes · frame lost Ratio is about the target A card taller than the root. It covers the whole root, yet the overlap is only 0.6 of the card. fills root · ratio 0.6 intersectionRatio divides the overlap by the target’s own area. A card taller than the screen can fill the viewport while its ratio stays near 0.6. Include 0 when you need the exit Which crossings fire a callback, per threshold list fully in starts leaving isIntersecting is true when the boxes overlap at all. A threshold of [1] fires when the card becomes fully visible and when it stops being fully visible. It stays quiet when the last pixel leaves. A list of [0, 1] includes that exit. Boxes, not pixels A modal covers the card. The observer still reports the full overlap. reported: 100% rootMargin and the ancestor A dashed box 200 pixels outside the root. The card overlaps the dashed box before it reaches the real root. counts before visible rootMargin: '200px' grows the root, the way CSS margin grows a box. A negative margin waits until the card is further in. The root you pass has to be an ancestor of the target. root: null means the viewport. One observer, many targets One observer watches three headings. The entry for the heading that moved names it in entry.target. 1 observer The first callback is the current state observe, then a first entry that is a reading, then later entries that are crossings. It arrives on a later task. The card can already be visible during the first paint. Treat that first entry as a reading, and later entries as crossings. Native lazy loading versus an observer <img loading="lazy">: browser picks the distance observer: component mounts, custom roots, one-shot prefetch The browser already defers images with its own distance. Reach for an observer when the decision is a component mount, a custom scroll root, a threshold, or a one-shot prefetch. Time is separate The card is half visible from the start. A one second timer you own runs alongside. When it completes, count the impression. threshold 0.5 met your timer 1 second “Half visible for one second” is a threshold of 0.5 plus a timer you clear when the ratio falls. The observer has no clock.
4. Beside a window
A window mounts the rows on screen. One sentinel is positioned at the real end of the list and observed. The callback fetches the next page. The other rows stay unmounted. mounted rows sentinel · observe once Windowing decides which rows exist. The observer watches one element that does exist. Position that sentinel at the end of the full height, including the spacer, so the next page can load before the reader hits the last mounted row.
1. Count the scroll. Count the callback.
Any pixel Half the card The whole card Tall card Cover it Reset counts Move the card Scrollport with one observed card Taller than the viewport Shorter than the viewport Modal on top The boxes overlap. The boxes do not overlap. The modal paints over the card. The overlap is still reported. This card is taller than the scrollport, so its ratio cannot reach 1. The card fills the scrollport. The ratio divides the overlap by the card, so it stays under 100%. Observer callbacks Waiting for the first observation. Waiting for the first intersection reading. Lazy image A margin of a couple hundred pixels starts the fetch while the image is still below the fold. Unobserve after it loads. Next page One empty element at the real end of a windowed list. Threshold 0. The callback asks for the next page, then ignores repeats until that request settles. Pause when the frame drops below half. Play when it crosses back. The observer replaces a scroll listener that would call getBoundingClientRect every frame. Half the card, held for one second. The threshold reports the half. A timer you own reports the second. Clear it if the ratio falls. Scroll spy One observer, every heading. The entry’s target is the heading that crossed. The link for the heading nearest the top is the current one. A link nears the viewport. One callback fetches the route. Unobserve so a later scroll does not fetch it again.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.