How to Implement Lazy Loading for Images
· Category: Web Performance
Short answer
Lazy loading defers off-screen images until the user scrolls near them. This reduces initial page weight and improves LCP.
Steps
- Add
loading="lazy"to<img>tags for native browser lazy loading. - For background images, use the Intersection Observer API to detect visibility.
- Place a small placeholder or low-quality image placeholder (LQIP) while loading.
- Set explicit width and height attributes to prevent layout shifts.
- Test with Chrome DevTools by throttling the network.
Tips
- Do not lazy-load above-the-fold images; preload them instead.
- Use responsive images with
srcsetto serve appropriate sizes. - Consider using a lazy-loading library for complex masonry layouts.
Common issues
- Images without dimensions cause CLS when they load.
- Older browsers may not support native lazy loading; use a polyfill.