Hiprup

What is lazy loading in JavaScript?

Lazy loading defers loading resources until they're actually needed, speeding up the initial page load.

  • Images / iframes — the native loading="lazy" attribute loads them as they near the viewport.

  • IntersectionObserver — detect when an element scrolls into view, then load its content.

  • Code — dynamic import() loads JavaScript modules on demand.

Benefit: less to download upfront — faster first paint and less wasted bandwidth.

// Image lazy loading (native)
<img src="photo.jpg" loading="lazy" alt="Photo" />

// Image lazy loading (IntersectionObserver)
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // Load actual image
      observer.unobserve(img);   // Stop observing
    }
  });
}, { rootMargin: '200px' }); // Start loading 200px before visible

document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));

// Module lazy loading
async function showChart() {
  const { Chart } = await import('chart.js'); // Load on demand
  const chart = new Chart(canvas, config);
}

// Route lazy loading (React-style)
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
// Only downloads Dashboard code when navigated to

Native loading='lazy' defers image loading until near viewport. IntersectionObserver provides custom control with rootMargin for preloading. Module lazy loading uses dynamic import() to load heavy libraries on demand.

Route lazy loading loads page components only when navigated to. All reduce initial bundle size and improve load performance.

Show all three types: images (loading='lazy'), modules (dynamic import()), and routes (React.lazy). IntersectionObserver with rootMargin for preloading shows production awareness.

The key metric: reduced initial bundle size → faster page load.

What is lazy loading in JavaScript? | Hiprup