π§ What Is Lazy Loading?
Lazy loading delays the loading of off-screen content β typically images β until they're needed (i.e., scrolled into view). This helps:
- Reduce initial page size
- Improve loading speed
- Increase your Largest Contentful Paint (LCP) score
- Minimize Cumulative Layout Shift (CLS)
π οΈ 1. Native Lazy-Loading with loading="lazy"
Simply add the loading
attribute to your <img>
tag:
<img src="product.jpg" alt="Product Image" loading="lazy" width="600" height="400">
β Best Practices:
- Always define
width
andheight
to avoid CLS (layout shift) - Use descriptive
alt
text for accessibility and SEO - Only apply to below-the-fold images
πΌοΈ 2. Responsive Lazy-Loading with srcset
Serve different image sizes for different screen widths using srcset
and sizes
:
<img
src="product-600.jpg"
srcset="product-400.jpg 400w, product-800.jpg 800w"
sizes="(max-width: 600px) 100vw, 600px"
loading="lazy"
alt="Responsive product"
width="600"
height="400">
This prevents mobile users from downloading large desktop images β saving bandwidth and improving load speed.
β 3. Don't Lazy-Load Above-the-Fold Content
Avoid lazy-loading content visible when the page first loads, such as:
- Hero banners
- Logos
- First images in articles
Doing so can hurt your LCP score (a Core Web Vital).
<!-- DO NOT lazy-load above-the-fold images -->
<img src="hero.jpg" alt="Hero Banner" width="1200" height="600">
π§ͺ 4. Test Your Performance with Web Vitals Tools
After implementation, test your improvements using:
- β Google PageSpeed Insights
- β Lighthouse in Chrome DevTools
- β WebPageTest.org
Look for improvement in:
- LCP (Largest Contentful Paint)
- CLS (Cumulative Layout Shift)
- TBT (Total Blocking Time)
π 5. Lazy-Load Background Images with IntersectionObserver
HTML's loading="lazy"
doesnβt apply to background images in CSS. For that, use JavaScript:
const lazyBackgrounds = document.querySelectorAll(".lazy-bg");
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.backgroundImage = `url(${entry.target.dataset.bg})`;
observer.unobserve(entry.target);
}
});
});
lazyBackgrounds.forEach(bg => {
observer.observe(bg);
});
HTML example:
<div
class="lazy-bg"
data-bg="background.jpg"
style="min-height: 300px;"></div>
π Final Thoughts
With a few lines of HTML and a little JS, you can:
- Speed up your site
- Boost your Core Web Vitals
- Improve your user experience
Lazy-loading is a quick win with a big impact β so use it wisely!
Top comments (0)