Lazy Loading
Lazy Loading
Section titled “Lazy Loading”Introduction
Section titled “Introduction”Lazy loading defers loading of resources (images, scripts, components) until they’re actually needed — typically when they become visible or when user interaction requires them.
Topics Covered
Section titled “Topics Covered”- Images & Media — Native lazy loading and IntersectionObserver for images
- Components & Scripts — Lazy loading code with React.lazy and dynamic imports
- Intersection Observer — Custom lazy loading control
Why Do We Need This?
Section titled “Why Do We Need This?”Lazy loading reduces initial page load time, saves bandwidth, and improves performance for users who may never interact with certain content.
Image Lazy Loading
Section titled “Image Lazy Loading”<!-- Native lazy loading (modern browsers) --><img src="image.jpg" loading="lazy" alt="Lazy loaded image">
<!-- Intersection Observer for custom control --><img data-src="image.jpg" alt="Lazy loaded" class="lazy">// Intersection Observer for imagesconst imageObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; img.classList.add('loaded'); imageObserver.unobserve(img); } });}, { rootMargin: '200px' });
document.querySelectorAll('img[data-src]').forEach(img => { imageObserver.observe(img);});Component Lazy Loading
Section titled “Component Lazy Loading”// React: React.lazy + Suspenseconst HeavyComponent = React.lazy(() => import('./HeavyComponent'));
<Suspense fallback={<Spinner />}> <HeavyComponent /></Suspense>;
// Dynamic import for any modulebutton.addEventListener('click', async () => { const { renderChart } = await import('./heavy-chart.js'); renderChart();});Summary
Section titled “Summary”- Defer non-critical resources until needed
- Native
loading="lazy"for images - Intersection Observer for custom control
React.lazy()/ dynamicimport()for code splitting- Reduces initial bundle size and improves load time