InterviewHubPRO
Section Overview
Q503

Question 503 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

97%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

How does the Intersection Observer API work?

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or the viewport.

Basic usage:

javascript
 const observer = new IntersectionObserver((entries) => {
   entries.forEach(entry => {
     if (entry.isIntersecting) {
       console.log('Element is visible');
       entry.target.classList.add('visible');
     } else {
       console.log('Element is not visible');
     }
   });
 });

 const target = document.querySelector('.observe-me');
 observer.observe(target);

Lazy loading images:

javascript
 const imageObserver = new IntersectionObserver((entries, observer) => {
   entries.forEach(entry => {
     if (entry.isIntersecting) {
       const img = entry.target;
       img.src = img.dataset.src;
       img.classList.add('loaded');
       observer.unobserve(img); // Stop observing after loading
     }
   });
 });

 document.querySelectorAll('img[data-src]').forEach(img => {
   imageObserver.observe(img);
 });

Infinite scrolling:

javascript
 const infiniteScroll = new IntersectionObserver((entries) => {
   entries.forEach(entry => {
     if (entry.isIntersecting) {
       loadMoreContent();
     }
   });
 }, {
   rootMargin: '100px' // Trigger 100px before reaching the element
 });

 const sentinel = document.querySelector('.load-more-trigger');
 infiniteScroll.observe(sentinel);

Options:

javascript
 const options = {
   root: null, // viewport (default)
   rootMargin: '0px 0px -100px 0px', // Shrink observation area
   threshold: [0, 0.25, 0.5, 0.75, 1] // Trigger at multiple visibility levels
 };

 const observer = new IntersectionObserver((entries) => {
   entries.forEach(entry => {
     console.log(`Visibility: ${entry.intersectionRatio * 100}%`);
   });
 }, options);

Tracking visibility time:

javascript
 let visibilityStartTime;

 const visibilityObserver = new IntersectionObserver((entries) => {
   entries.forEach(entry => {
     if (entry.isIntersecting) {
       visibilityStartTime = Date.now();
     } else if (visibilityStartTime) {
       const visibilityDuration = Date.now() - visibilityStartTime;
       console.log(`Element was visible for ${visibilityDuration}ms`);
       visibilityStartTime = null;
     }
   });
 });