About this snippet

Improve website performance by implementing image lazy loading. Images are only loaded when they are about to enter the viewport, saving bandwidth and speeding up initial page load.

Size
2.6 KB
Uses
HTML, CSS, JavaScript
Loads
placehold.co
Views
556

Collections

<img data-src="https://placehold.co/300x200/E8117F/white?text=Image+1" alt="Lazy Loaded Image 1" class="lazy">
<div style="height:800px;">Scroll down to see more images.</div>
<img data-src="https://placehold.co/300x200/367EAA/white?text=Image+2" alt="Lazy Loaded Image 2" class="lazy">
<div style="height:800px;">Scroll down...</div>
<img data-src="https://placehold.co/300x200/A239F9/white?text=Image+3" alt="Lazy Loaded Image 3" class="lazy">
img.lazy {
  display: block;
  margin-bottom: 10px;
  background-color: #f0f0f0; /* Placeholder background */
  min-height: 100px; /* Placeholder height */
  border: 1px solid #ccc;
}
img.lazy[src] {
  /* Styles for when the image has loaded */
  background-color: transparent;
  border: 1px solid transparent;
}
document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

  if ("IntersectionObserver" in window) {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Fallback for browsers that don't support IntersectionObserver
    let active = false;

    const lazyLoad = function() {
      if (active === false) {
        active = true;

        setTimeout(function() {
          lazyImages.forEach(function(lazyImage) {
            if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") {
              lazyImage.src = lazyImage.dataset.src;
              lazyImage.classList.remove("lazy");

              lazyImages = lazyImages.filter(function(image) {
                return image !== lazyImage;
              });

              if (lazyImages.length === 0) {
                document.removeEventListener("scroll", lazyLoad);
                window.removeEventListener("resize", lazyLoad);
                window.removeEventListener("orientationchange", lazyLoad);
              }
            }
          });
          active = false;
        }, 200);
      }
    };
    document.addEventListener("scroll", lazyLoad);
    window.addEventListener("resize", lazyLoad);
    window.addEventListener("orientationchange", lazyLoad);
    lazyLoad(); // Initial check
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save