The old way
Tracking whether an element is visible once meant listening to scroll events and measuring positions. That fires constantly and forces layout reads, hurting performance.
The observer
The Intersection Observer API watches a target element and tells you asynchronously when it crosses a threshold of visibility relative to a root, usually the viewport. The browser does the math efficiently, off the main work path.
How it works
- You create an observer with a callback and options.
- You call observe on each target element.
- The callback receives entries describing each target and its isIntersecting flag.
Common uses
- Lazy loading images as they approach the screen.
- Triggering animations when content scrolls into view.
- Implementing infinite scroll by watching a sentinel near the list end.
Key idea
The Intersection Observer efficiently reports when elements enter or leave the viewport via a callback, replacing costly scroll listeners.