JavaScript Course
JavaScript
/
Advanced

Intersection Observer

Definition

A browser API that provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Explain Like I'm New

Instead of using a scroll listener that fires 1000 times a second to do complex math to ask 'Is this image on the screen yet?', you hire a security guard (Intersection Observer). You tell the guard, 'Tap me on the shoulder the exact second this image enters the screen.'

Real World Example

Infinite Scrolling. You place an invisible `<div>` at the bottom of your list. When the Intersection Observer sees that `<div>` enter the screen, it fetches the next page of API results.

Common Use Cases

  • •Lazy loading images
  • •Infinite scrolling
  • •Triggering animations on scroll

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Why is Intersection Observer better than a `scroll` event listener?

intermediate

  • What is the `threshold` option?

advanced

  • How do you stop observing an element once it has loaded?

Flash Cards

Question

Why is it better than a scroll listener?

Click to reveal answer
Answer

Scroll listeners run synchronously on the main thread, causing severe performance jank. Intersection Observer runs asynchronously off the main thread, vastly improving performance.

Question

What is the threshold?

Click to reveal answer
Answer

It is a number between 0 and 1 indicating how much of the element must be visible before the callback fires. `0` means '1 pixel has entered'. `1.0` means 'The entire element is 100% visible on screen'.