Deep dive into how IntersectionObserver works
This is a delightfully nerdy exploration of how IntersectionObserver works, its quirks and caveats, and how it can be used to create a JavaScript position: sticky
event as a bonus.
The Intersection Observer API 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.
This is a delightfully nerdy exploration of how IntersectionObserver works, its quirks and caveats, and how it can be used to create a JavaScript position: sticky
event as a bonus.
Here’s a secret: You may not need
scroll
events in your next app. Using anIntersectionObserver
, I show how you can fire a custom event whenposition:sticky
elements become fixed or when they stop sticking. All without the use of scroll listeners.[…]
One of the practical limitations of using CSS sticky position is that it doesn’t provide a platform signal to know when the property is active. In other words, there’s no event to know when an element becomes sticky or when it stops being sticky.
What do infinite scrolling, lazy loading, and online advertisements all have in common?
They need to know about—and react to—the visibility of elements on a page!
Unfortunately, knowing whether or not an element is visible has traditionally been difficult on the Web. Most solutions listen for scroll and resize events, then use DOM APIs like getBoundingClientRect() to manually calculate where elements are relative to the viewport. This usually works, but it’s inefficient and doesn’t take into account other ways in which an element’s visibility can change, such as a large image finally loading higher up on the page, which pushes everything else downward.
Things get worse for advertisements, since real money is involved. As Malte Ubl explained in his presentation at JSConf Iceland, advertisers don’t want to pay for ads that never get displayed. To make sure they know when ads are visible, they cover them in dozens of tiny, single-pixel Flash movies whose visibility can be inferred from their framerate. On platforms without Flash, like smartphones, advertisers set up timers to force browsers to recalculate the position of each ad every few milliseconds.
These techniques kill performance, drain batteries, and would be completely unnecessary if the browser could just notify us whenever an element’s visibility changed.
That’s what IntersectionObserver does.