Web APIs — Intersection Observer
What is an Intersection Observer?
It is a Web API which provides a way to asynchronously observe changes in the intersection(position or visiblity) of a target element with an ancestor element or with a top-level document’s viewport.
What is the difference in an observer and an event?
The main difference is that the observer works asynchronously and doesn’t affect the main thread much but the event runs synchronously using the main thread and affecting the performance.
Why do we need it ?
The main reason of using the Intersection observer is that all the code runs on the main thread in browser.
Earlier, it involved event handlers and loops calling methods like Element.getBoundingClientRect()
to build up the needed information for every element affected.
Example:- Lets consider a website that uses infinite scrolling, advertisements, animations etc. Each of these has its own intersection detection routines, all running on the main thread. As the user scrolls the page, these intersection detection routines are firing constantly during the scroll handling code, resulting in a bad experience for the user.
How Intersection observer helps?
- lets code register a callback function that is executed whenever an element they wish to monitor enters or exits ancestor element (or the viewport).