Course contentsShow
← Web Development
Lesson 1254 of 2,98222. Responsive Images and MediaFree lesson

Custom Lazy Loading Implementation

Building a JavaScript lazy loader with data-src attributes and Intersection Observer.

Custom Lazy Loading Implementation

You'll learn: How to build your own JavaScript-powered lazy loader using data attributes and the Intersection Observer API to load images on demand.

Why Build a Custom Lazy Loader?

While loading="lazy" is great, sometimes you need more control: custom loading thresholds, placeholder effects, or support for older browsers. A custom implementation gives you that flexibility while applying the Intersection Observer concepts you've learned.

The Core Pattern

The strategy is simple:

  1. Mark images with data-src instead of src (preventing immediate load)
  2. Use Intersection Observer to watch when images enter the viewport
  3. Swap data-src to src when the image becomes visible

Basic Implementation

// Select all images with data-src
const lazyImages = document.querySelectorAll('img[data-src]');

// Create an Intersection Observer
const imageObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      
      // Load the actual image
      img.src = img.dataset.src;
      
      // Stop observing this image
      observer.unobserve(img);
    }
  });
});

// Start observing each lazy image
lazyImages.forEach(img => imageObserver.observe(img));

HTML Setup

<img data-src="large-photo.jpg" alt="Scenic view">

The browser sees an <img> without a src, so it doesn't fetch anything. Your JavaScript "activates" it when needed.

Key Takeaway: A custom lazy loader uses data-src to defer image requests and Intersection Observer to trigger loading when images approach the viewport, giving you full control over the lazy-loading behavior.