Lazy loading images using IntersectionObserver - example code

PHOTO EMBED

Sat May 28 2022 05:51:48 GMT+0000 (Coordinated Universal Time)

Saved by @rbsuperb #undefined

document.addEventListener("DOMContentLoaded", function() {

  var lazyloadImages;    

​

  if ("IntersectionObserver" in window) {

    lazyloadImages = document.querySelectorAll(".lazy");

    var imageObserver = new IntersectionObserver(function(entries, observer) {

      entries.forEach(function(entry) {

        if (entry.isIntersecting) {

          var image = entry.target;

          image.src = image.dataset.src;

          image.classList.remove("lazy");

          imageObserver.unobserve(image);

        }

      });

    });

​

    lazyloadImages.forEach(function(image) {

      imageObserver.observe(image);

    });

  } else {  

    var lazyloadThrottleTimeout;

    lazyloadImages = document.querySelectorAll(".lazy");

    
content_copyCOPY

https://codepen.io/imagekit_io/pen/BPXQZZ