Introduction to Lazy Loading Images
Lazy loading images is a performance optimization technique that delays loading images until they are about to enter the viewport. This reduces initial page load time, saves bandwidth, and improves user experience, especially on mobile devices.
Modern browsers support native lazy loading, making it easier than ever to implement without additional JavaScript libraries.
Why Lazy Loading Matters for Performance
Images are often the largest assets on a webpage. Loading all images upfront can significantly increase load time and negatively impact Core Web Vitals like Largest Contentful Paint (LCP). Lazy loading ensures only visible images are loaded first.
Native Lazy Loading (Recommended)
The simplest way to implement lazy loading is using the native loading attribute supported by modern browsers.
<img src="image.jpg" loading="lazy" alt="Example image" />
This method requires no JavaScript and works efficiently for most use cases.
Using Intersection Observer (Advanced)
For more control, you can use the Intersection Observer API to load images dynamically when they enter the viewport.
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
images.forEach(img => observer.observe(img));
Avoid Lazy Loading Above-the-Fold Images
Do not lazy load images that are visible on initial load (such as hero images). These should be loaded eagerly to improve LCP.
<img src="hero.jpg" loading="eager" alt="Hero image" />
Prevent Layout Shift (CLS)
Always define width and height attributes or use aspect-ratio to reserve space for images. This prevents layout shifts when images load.
<img src="image.jpg" width="800" height="600" loading="lazy" />
Best Practices for Image Optimization
Use modern formats like WebP or AVIF, compress images, and serve responsive images using srcset to ensure optimal performance across devices.
<img src="image.webp" srcset="image-480.webp 480w, image-800.webp 800w" sizes="(max-width: 600px) 480px, 800px" loading="lazy" />
Conclusion
Lazy loading is a simple yet powerful technique to improve web performance. By combining native lazy loading, proper image sizing, and modern formats, you can significantly enhance user experience and SEO performance.
Summary
Performance
Apply these steps incrementally to preserve UX while improving runtime and load stability.
Maintainability
Keep implementation modular so future updates can be tested and shipped with confidence.