Intersection Observer API 

What is Intersection Observer

  • From MDN:
    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.

 

  • In short: Triggers a callback based on the visibility/overlapping of a dom object to its parent

Possible Use Cases

  • Lazy loading images
  • Highlight active nav item from a sticky nav based on scroll position
  • auto play/pause video/carousals when scrolled to/out
  • Implementing "infinite scrolling" web sites
  • Reporting of visibility of advertisements

Deferred functionality based on the elements’ visibility

Intersection Observer Vs scroll Event

  • Events: reacts synchronously for every occurrence of the Event, affecting the main thread’s responsiveness.
  • Observers:  are asynchronously and non-blocking without affecting performance
  • IntersectionObserver: provide a very handy pre-computed properties. no need for expensive properties/methods like getBoundingRect, clientHeight, scrollTop etc
const observer = new IntersectionObserver(
  // callback
  function callback(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) { 
        // do something
        // lazy load, play video, update sticky nav ...etc
        // entry.boundingClientRect
        // entry.intersectionRatio
        // entry.intersectionRect
        // entry.target
      }
    })
  },
  // options
  { 
    // null for viewport or a dom element
    root: null, 
    // extends or shrinks the roots capturing frame
    rootMargin: '0px 0px 0px 0px', 
    // percentage of such intersection at which Observer should react
    threshold: 0, // accepts values from 0 to 1, 
  } 
)
observer.observe(target)

intersection area = 50%

rootMargin: '0px 0px 0px 0px'

threshold: 0.5

Credits

Intersection Observer API

By Mohammad Mohammad

Intersection Observer API

A short introduction to the Intersection Observer API. Material in these slides are mostly from the comprehensive article https://www.smashingmagazine.com/2018/01/deferring-lazy-loading-intersection-observer-api/

  • 835