Lazy loading defers loading non-critical resources until they're needed. For images, use loading="lazy" attribute. For JavaScript, use dynamic import() or React.lazy(). This reduces initial page load time and saves bandwidth.
What Can Be Lazy Loaded:
Native Browser Support:
loading="lazy" for imagesloading="lazy" for iframesJavaScript Lazy Loading:
import() for modulesReact.lazy() for componentsWhen to Lazy Load:
<!-- Lazy load images -->
<img src="below-fold.jpg" loading="lazy" alt="Description" />
<!-- Eager load above-the-fold images -->
<img src="hero.jpg" loading="eager" alt="Hero" />
<!-- Lazy load iframes -->
<iframe
src="https://youtube.com/embed/video"
loading="lazy"
title="Video"
></iframe>
<!-- Lazy load with intersection observer fallback -->
<img
class="lazy"
src="placeholder.jpg"
data-src="actual-image.jpg"
alt="Description"
/>
<script>
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
observer.unobserve(img);
}
});
});
document.querySelectorAll('.lazy').forEach(img => observer.observe(img));
</script>