The loading='lazy' Attribute
What you'll learn: How to use the loading='lazy' attribute to defer loading offscreen images and iframes until the user scrolls near them.
The Problem with Eager Loading
By default, when a browser parses your HTML, it immediately starts downloading all images and iframes on the page—even those far below the fold that the user may never see. This wastes bandwidth and slows down initial page load, especially on slower connections or mobile devices.
How loading='lazy' Works
The loading attribute tells the browser when to load a resource. Setting it to 'lazy' instructs the browser to defer downloading that image or iframe until the user scrolls close enough to view it.
Think of it like a library that doesn't pull books from storage until you walk near that shelf—saving energy and space until actually needed.
Basic Syntax
<img src="photo.jpg" alt="Landscape" loading="lazy">
<iframe src="map.html" loading="lazy"></iframe>
The browser decides the exact trigger distance (usually a few hundred pixels before the element enters the viewport). You don't control the threshold—the browser optimizes it for performance.
When to Use It
- Below-the-fold images: Any image not immediately visible on page load
- Long pages: Articles with many images throughout
- Embedded iframes: Maps, videos, or widgets lower on the page
When NOT to Use It
- Above-the-fold images: The hero image or logo should load immediately (use
loading="eager"or omit the attribute) - If omitted,
loadingdefaults to"eager"(immediate loading)
Browser Support Note
Native lazy loading is widely supported in modern browsers. For older browsers, the attribute is simply ignored—images load normally, providing a graceful fallback.
Key Takeaway: Use loading="lazy" on offscreen <img> and <iframe> elements to improve page load performance by deferring their download until the user scrolls nearby.