Lazy Loading Images and Iframes
Implements native lazy loading for images and iframes using the loading attribute, with Intersection Observer fallback for older browsers.
Code
<!-- Native lazy loading -->
<img src="hero.jpg" alt="Hero" loading="eager" width="1200" height="600">
<img src="image1.jpg" alt="Image 1" loading="lazy" width="400" height="300">
<img src="image2.jpg" alt="Image 2" loading="lazy" width="400" height="300">
<img src="image3.jpg" alt="Image 3" loading="lazy" width="400" height="300">
<iframe src="video-player.html" loading="lazy"
width="560" height="315"
title="Video player"></iframe>
<!-- With fade-in effect -->
<img class="lazy-img"
src="placeholder.svg"
data-src="actual-image.jpg"
alt="Description"
width="400" height="300">
<style>
.lazy-img {
opacity: 0;
transition: opacity 0.3s;
}
.lazy-img.loaded {
opacity: 1;
}
</style>
<script>
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.add('loaded');
observer.unobserve(img);
}
});
}, {
rootMargin: '50px 0px',
threshold: 0.01
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
} else {
document.querySelectorAll('img[data-src]').forEach(img => {
img.src = img.dataset.src;
});
}
</script>Native lazy loading (loading="lazy") defers offscreen images/iframes until needed, improving initial page load. loading="eager" loads immediately. For older browsers, IntersectionObserver provides a fallback with custom root margin and threshold. Always set width/height to prevent layout shift. rootMargin pre-loads images before they enter viewport.
Interactive Tools for This Topic
HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
Report a problem with this exampleOpens a pre-filled issue on GitHub.