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:
- Mark images with
data-srcinstead ofsrc(preventing immediate load) - Use Intersection Observer to watch when images enter the viewport
- Swap
data-srctosrcwhen 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.