Lazy Loading images with IntersectionObserver

Smashing Magazine has an extensive article on using the aforementioned IntersectionObserver to lazy load image assets on your page.

The article first explains the difference between a regular Event and an Observer, before diving into the IntersectionObserver.

const images = document.querySelectorAll('[data-src]');
const config = {
  rootMargin: '0px 0px 50px 0px',
  threshold: 0
};
let loaded = 0;

let observer = new IntersectionObserver(function (entries, self) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // console.log(`Image ${entry.target.src} is in the viewport!`);
      preloadImage(entry.target);
      // Stop watching and load the image
      self.unobserve(entry.target);
    }
  });
}, config);

images.forEach(image => {
  observer.observe(image);
});

Now You See Me: How To Defer, Lazy-Load And Act With IntersectionObserver

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.