Recently while exploring the frontend world, I came upon a interesting feature of JavaScript -> Intersection Observer. Intersection Observer API is one of the most underutilized and unheard JavaScript’s features.
Intro
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.
However its sounds complex but it provides a simple solution for the most general problem: knowing when an element becomes visible of invisible to the use.
Why It Matters
scroll event was the go-to method for developers when it comes to determine whether an element is visible on screen. Developers often had to perform manual calculations optimizations to ensure performance remained optimal, especially when tracking several elements. This approach could become inefficient while tracking several elements as the browser repeatedly recalculated positions during scrolling.
How It Works
The Intersection Observer basically revolves around three components:
-
Observer: The _IntersectionObserver _object watches one or more elements.
-
Callback: A function is triggered whenever the visibility of a target element changes.
-
Options: Configuration parameters like root, rootMargin, and threshold.
- root: Defines viewport for checking visibility. The default value is null which refers to browser;s viewport.
- rootMargin: A margin around the root element, similar to CSS margin. Positive value grows/adds while negative value shrinks/subtracts the bounding box of the root element.
- threshold : Specifies the percentage of the target element’s visibility that must be reached before the observer’s callback is triggered. It ranges from 0 (0%) to 1 (100%)
Implementation
To get started, create an instance of IntersectionObserver
const lazyObserver = new IntersectionObserver(handleLazyImage, {
rootMargin: "-10px", //10px margin was used in the container to address that margin
root: lazyImageContainer, // Custom container as the root
threshold: 0.25, // Trigger when 10% of the image is visible in the container
});
In the example above, handleLazyImage is callback function while the remaining properties are config options.
After the observer is instantiated, simply start observing the target elements:
lazyImages.forEach((img) => lazyObserver.observe(img));
For more details, you can checkout theGithub repository.
Practical Use cases
-
Infinite Scrolling: Detect when the user reaches the end of the page and fetch new data via API calls.
-
Lazy Loading: Load images or other content as they come into view during scrolling.
-
Ad Visibility Reporting: Track whether advertisements are visible to users to calculate ad revenue.
-
Task and Animation Control: Trigger tasks or animations only when the user is likely to see the results, improving performance and user experience.
Conclusion
The Intersection Observer API represents a significant step forward in how we handle viewport-based interactions in web applications. It provides a clean, efficient solution for many common use cases while improving performance and reducing complexity. Whether you’re implementing lazy loading, infinite scrolling, or scroll-based animations, the Intersection Observer API should be your go-to tool.
Give it a try in your next project – your users (and your performance metrics) will thank you!
Source link
lol