Lazy Loading Images with custom JavaScript

Quickly enhance your website’s performance by implementing lazy loading for images with this custom JavaScript snippet.

JavaScript
// Lazy Loading Images with Custom JavaScript

document.addEventListener("DOMContentLoaded", function () {
  var lazyImages = document.querySelectorAll("img.lazy");

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

  var lazyLoadHandler = function () {
    lazyImages.forEach(function (lazyImage) {
      if (lazyImage.getBoundingClientRect().top < window.innerHeight && 
      		lazyImage.getBoundingClientRect().bottom > 0) {
        lazyImage.src = lazyImage.dataset.src;
        lazyImage.classList.remove("lazy");
      }
    });
  };

  window.addEventListener("scroll", lazyLoadHandler);
  window.addEventListener("resize", lazyLoadHandler);
});

Usage

To use this code, follow these steps:

  1. Add the lazy class to the <img> elements you want to lazy load.
  2. Set the data-src attribute to the actual image source (src).
  3. Include the above JavaScript snippet on your page.
HTML
<img src="placeholder.gif" class="lazy" data-src="full-size.jpg" width="500" height="500">

FAQs

How does lazy loading improve website performance?

Lazy loading delays the loading of non-essential resources, like images, until they are about to be viewed. This reduces initial page load times, leading to a faster user experience.

References

  1. MDN Web Docs – Intersection Observer API
  2. Google Developers – Lazy Loading Images

Leave a Reply