Skip to content
Lazy Loading — Explained with Examples

Lazy Loading — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

Lazy loading defers loading non-critical resources until needed, improving initial page load time and reducing bandwidth usage.

Lazy loading delays loading of images, videos, iframes, scripts, or components until they are near the viewport or required by the user. The Intersection Observer API detects when elements enter the viewport. Native loading="lazy" attribute works for images and iframes. For JavaScript components, dynamic imports (import()) load code on demand. Lazy loading applies to routes, components below the fold, images in carousels, and third-party widgets.

Think of lazy loading like a buffet-goer who only puts food on their plate that they plan to eat now, rather than piling everything onto their plate at once (eager loading). They go back for more when ready. This means their plate is lighter initially, and they never waste food on items they skip.

Lazy loading can dramatically improve Core Web Vitals, especially Largest Contentful Paint (LCP) and Time to Interactive (TTI).

<!-- Native lazy loading for images -->
<img src="hero.jpg" alt="Hero" loading="lazy">
<iframe src="widget.html" loading="lazy"></iframe>

<!-- Fallback: Intersection Observer -->
<img data-src="large-photo.jpg" alt="Lazy" class="lazy">
// Intersection Observer for lazy loading
const lazyImages = document.querySelectorAll('img[data-src]');

const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.removeAttribute('data-src');
            observer.unobserve(img);
        }
    });
}, { rootMargin: '200px' });  // Start loading 200px before visible

lazyImages.forEach(img => imageObserver.observe(img));

// Code-level lazy loading (dynamic imports)
document.getElementById('load-chart').addEventListener('click', async () => {
    const { ChartModule } = await import('./ChartModule.js');
    ChartModule.render();
});
/* Prevent layout shift for lazy images */
img[loading="lazy"] {
    width: 100%;
    aspect-ratio: 16 / 9;
    background: #f0f0f0;
}

Lazy load below-the-fold content, but do not lazy load the hero image or critical above-the-fold content (it hurts LCP). Use appropriate placeholder techniques to prevent layout shift.

Code Splitting, PWA, Performance, Intersection Observer

Code Splitting for Lazy Loading

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro