Observer APIs: Intersection, Mutation & Resize
Stop using terrible scroll and resize event hacks. Discover the modern, highly-optimized Observer APIs that let you respond to layout and DOM changes efficiently.
The Performance Saviors
In the past, if you wanted to know when an element scrolled onto the screen, you had to attach an event listener to the window.onscroll event.
Because the user scrolls hundreds of pixels a second, your function would fire hundreds of times a second, bringing the browser to a crawl. The modern **Observer APIs** were created to solve this.
The Big Three
1. IntersectionObserver: Tells you exactly when an element enters or leaves the screen (or another container). Used for lazy-loading images and infinite scrolling.
2. ResizeObserver: Tells you when a specific element changes its width or height. It is a massive improvement over listening to window.onresize.
3. MutationObserver: Tells you when the DOM tree itself changes, such as a node being added/removed or a class name changing.
The Standard Pattern
All observers follow the exact same architectural pattern:
First, you instantiate the observer with a callback function: const observer = new IntersectionObserver((entries) => { ... }).
Second, you tell it what element to watch: observer.observe(myDiv).
When the criteria is met, the browser fires your callback asynchronously, passing an array of entries containing the new data.
The Intersection Simulator
Scroll the container below. Watch how the observer only fires its callback at the exact moment the target element crosses the threshold, saving immense amounts of CPU power compared to a scroll listener.
The Intersection Simulator
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
console.log("isIntersecting:", entry.isIntersecting);
});
observer.observe(targetElement);
observer.disconnect();
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Stop using
scrollandresizeevent listeners for layout calculations. IntersectionObserverfires when elements enter or leave a container.ResizeObserverfires when an element's physical dimensions change.MutationObserverfires when DOM nodes or attributes are modified.- Always call
observer.disconnect()to prevent memory leaks when elements are destroyed.
Done with this concept?
Mark it complete to track your progress. No login needed.