Skip to content

Lazy Loading

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.

Lazy loading reduces initial page load time, saves bandwidth, and improves performance for users who may never interact with certain content.

<!-- 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 images
const 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);
});
// React: React.lazy + Suspense
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
<Suspense fallback={<Spinner />}>
<HeavyComponent />
</Suspense>;
// Dynamic import for any module
button.addEventListener('click', async () => {
const { renderChart } = await import('./heavy-chart.js');
renderChart();
});
  • Defer non-critical resources until needed
  • Native loading="lazy" for images
  • Intersection Observer for custom control
  • React.lazy() / dynamic import() for code splitting
  • Reduces initial bundle size and improves load time