Knowledge Base

Lazy Loading Basics

Lazy loading defers loading of off-screen resources (like images) until they are needed, improving performance and reducing bandwidth usage.

Modern browsers support the native loading="lazy" attribute, but using IntersectionObserver gives more control and broader compatibility.

How it works

const observer = new IntersectionObserver((entries, obs) => {
  entries.forEach(entry => {
    if(entry.isIntersecting){
      const img = entry.target;
      img.src = img.dataset.src;
      img.onload = () => img.classList.add('loaded');
      obs.unobserve(img);
    }
  });
});

document.querySelectorAll('.lazy-img').forEach(img => observer.observe(img));

Live Demo

Demo Image 1 Demo Image 2 Demo Image 3 Demo Image 4

Benefits