DEV Community

Fourfold Tech
Fourfold Tech

Posted on

How to Lazy-Load Images with Native HTML and Boost Your Site's Core Web Vitals

🧠 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">
Enter fullscreen mode Exit fullscreen mode

βœ… Best Practices:

  • Always define width and height 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">
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 4. Test Your Performance with Web Vitals Tools

After implementation, test your improvements using:

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);
});
Enter fullscreen mode Exit fullscreen mode

HTML example:

<div
  class="lazy-bg"
  data-bg="background.jpg"
  style="min-height: 300px;"></div>
Enter fullscreen mode Exit fullscreen mode

🌟 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)