Image Lazy Loading

Lazy loading images for better performance.

Native Lazy Loading

Browser native (modern browsers)
 src="image.jpg" loading="lazy" alt="...">

For iframes
 src="video.html" loading="lazy"

Loading values
lazy // load when near viewport
eager // load immediately
auto // browser decides (default)

Intersection Observer

JavaScript lazy loading
const images = document.querySelectorAll(img[data-src]);

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      observer.unobserve(img);
    }
  });
});

images.forEach(img => observer.observe(img));

Responsive Images

srcset for different sizes

  src="image-800.jpg"
  srcset="
    image-400.jpg 400w,
    image-800.jpg 800w,
    image-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 400px, 800px"
  loading="lazy"
>

Progressive Images

Blur-up technique
1. Show tiny blurred placeholder
2. Load full image in background
3. Swap when loaded with fade transition

Low Quality Image Placeholder (LQIP)

  src="tiny-image-20px.jpg"
  data-src="full-image.jpg"
  class="blur"
>