Favorites

Lazy Loading: The Secret to Faster Web Pages

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Lazy Loading

What is lazy loading?

Lazy loading means waiting to load something until it's actually needed. On a long page full of images, there's no point downloading the photos at the very bottom before someone has even started reading. Lazy loading fetches those images only as the visitor scrolls towards them.

The benefits are simple:

  • Faster first view: the browser can focus on what's visible straight away.
  • Less data: images people never scroll to are never downloaded, which saves bandwidth for visitors on mobile plans, and for your server.
  • Less work for the device: fewer images to decode and display at once.

The best part is that for images and iframes, you no longer need any JavaScript at all.

Native lazy loading for images and iframes

Add loading="lazy" to an image or iframe, and the browser takes care of the rest:

<img src="mountains.jpg" alt="Snow-capped mountains at sunrise" width="1200" height="800" loading="lazy">

<iframe src="https://www.example.com/map" title="Map of our office" width="600" height="400" loading="lazy"></iframe>
  • loading="lazy" tells the browser it can wait until the element is close to the visible part of the page before downloading it. Browsers start loading a little early, so images are usually ready by the time they scroll into view.
  • width and height are essential. They let the browser reserve the right amount of space before the image arrives, so the page doesn't jump about as images load (a problem called layout shift). With CSS such as img { max-width: 100%; height: auto; }, the image still resizes responsively, keeping the same shape.
  • Iframes, such as embedded videos and maps, are often even heavier than images, so they're great candidates for lazy loading too.

Browser support: loading="lazy" works in Chrome and Edge, Firefox (121 onwards) and Safari (16.4 onwards), and has been Baseline widely available since June 2026. Browsers that don't support it just load the image normally, so there's no need for a fallback.

Responsive images and modern formats

Lazy loading works hand in hand with serving the right image size and format. Here's a lazy-loaded image that offers a modern AVIF version, a WebP fallback, and a JPEG for any browser that supports neither:

<picture>
  <source srcset="mountains.avif" type="image/avif">
  <source srcset="mountains.webp" type="image/webp">
  <img src="mountains.jpg" alt="Snow-capped mountains at sunrise" width="1200" height="800" loading="lazy">
</picture>

The loading attribute goes on the <img>, and it applies whichever source the browser picks.

Out of date: the original version of this post suggested JPEG 2000 as a modern format. Only Safari ever supported it, so stick with AVIF and WebP, which work in all major browsers.

Don't lazy-load the first screen

This is the most common lazy loading mistake. Images that are visible as soon as the page opens, such as a large hero image or the main photo of a product, should not be lazy loaded. Lazy loading makes the browser hold back until it has worked out the page layout, which delays exactly the images people see first.

The largest image near the top of the page is often what Google measures as the page's Largest Contentful Paint (LCP), the moment the main content appears. For that image, do the opposite of lazy loading, and tell the browser it's a high priority:

<!-- The hero image: load it straight away, with high priority -->
<img src="hero.jpg" alt="Our team at work" width="1600" height="900" fetchpriority="high">

<!-- Images further down the page: load them lazily -->
<img src="gallery-1.jpg" alt="…" width="800" height="600" loading="lazy">

Tip: as a rule of thumb, leave loading="lazy" off any image that might appear on the first screen on any device, including large phones and desktops, and add it to everything below.

How it works: IntersectionObserver

Sometimes you need lazy loading for something the loading attribute doesn't cover, such as a CSS background image, a heavy widget, or an animation that should only start when it's visible. For those, JavaScript's IntersectionObserver tells you when an element comes into view, without having to check the scroll position constantly.

Scroll through the box below. Each "photo" starts as a grey placeholder, and is only loaded as it approaches the visible area:

Results

Images loaded: 0 of 12

Illustration: Mountains at sunrise
Photo 1: Mountains at sunrise
Illustration: A calm lake
Photo 2: A calm lake
Illustration: Desert dunes
Photo 3: Desert dunes
Illustration: Hills at night
Photo 4: Hills at night
Illustration: Rolling green fields
Photo 5: Rolling green fields
Illustration: Red rock canyon
Photo 6: Red rock canyon
Illustration: Misty peaks
Photo 7: Misty peaks
Illustration: Golden autumn valley
Photo 8: Golden autumn valley
Illustration: Mountains at sunrise
Photo 9: Mountains at sunrise
Illustration: A calm lake
Photo 10: A calm lake
Illustration: Desert dunes
Photo 11: Desert dunes
Illustration: Hills at night
Photo 12: Hills at night

Here's the core of the code. Each image starts with its real address stored in a data-src attribute instead of src:

<img data-src="photo.jpg" alt="…" width="600" height="400" class="lazy">
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) return;

    const img = entry.target;
    img.src = img.dataset.src;     // start the real download
    img.removeAttribute('data-src');
    observer.unobserve(img);       // no need to watch it any more
  });
}, {
  rootMargin: '200px 0px'          // start loading 200px before it's visible
});

document.querySelectorAll('img.lazy').forEach((img) => observer.observe(img));
  • The callback runs whenever an observed element enters or leaves view. isIntersecting is true when it's at least partly inside.
  • rootMargin expands the area being watched, so loading starts a little before the image actually scrolls into view.
  • unobserve() stops watching an image once it's loaded.

For ordinary <img> elements, though, loading="lazy" does all of this for you, with no JavaScript, and the image still loads if scripts fail. Keep IntersectionObserver for the special cases.

Libraries: the original version of this post recommended lazy loading libraries. Most of them were created before native lazy loading existed, and for images and iframes they're no longer needed. Older techniques that check the scroll position on every scroll event are also best avoided, as they're much less efficient than IntersectionObserver.

Loading scripts later

JavaScript files can also slow a page down, because by default the browser stops building the page while it downloads and runs each script. Three tools help, and they work in slightly different ways:

TechniqueDownloadsRuns
<script defer>Straight away, without blocking the pageAfter the page has been built, in order
<script async>Straight away, without blocking the pageAs soon as it's downloaded, in any order
import() in JavaScriptOnly when your code asks for itWhen it arrives

Here's import() loading a chart library only when someone opens the statistics section, so visitors who never open it never download it:

statsButton.addEventListener('click', async () => {
  const { drawChart } = await import('./chart.js');
  drawChart(document.querySelector('#stats'));
});

Frameworks build on the same idea. React's lazy() and Vue's defineAsyncComponent(), for example, use import() to load components only when they're displayed.

Lazy rendering with content-visibility

CSS has its own form of laziness. content-visibility: auto tells the browser it can skip rendering (laying out and painting) a section until it's near the screen. On long pages with many sections, this can make the first view appear noticeably faster:

.article-section {
  content-visibility: auto;
  contain-intrinsic-size: auto 600px;  /* a size estimate until it's rendered */
}
  • content-visibility: auto skips rendering off-screen sections. The content is still in the page, so it can be found with the browser's find-in-page search and read by screen readers.
  • contain-intrinsic-size gives each skipped section an estimated height, so the scrollbar doesn't jump around. The auto keyword makes the browser remember the real size once a section has been rendered.

content-visibility works in all major browsers, and has been Baseline since September 2024. It's most worthwhile on long pages with lots of complex content, such as long articles, comment threads or product listings.

Common mistakes

  • Lazy loading the hero image. As covered above, it delays exactly what people see first.
  • Leaving out width and height. Without them, the page jumps as each image arrives. If you can't set them in the HTML, use the CSS aspect-ratio property to reserve the space instead.
  • Forgetting alternative text. Lazy loaded images still need a meaningful alt attribute, or alt="" if they're purely decorative.
  • Hiding content behind interaction. Search engines don't scroll or click. Content that only loads when someone clicks a button, or scrolls in a certain way, may not be seen by search engines. loading="lazy" and IntersectionObserver are both search-friendly, because search engines can render the page as if everything were in view.
  • Lazy loading everything. Small icons and logos aren't worth it. Focus on large images, embeds and heavy sections further down the page.

A quick checklist

  1. Add loading="lazy" to images and iframes below the first screen.
  2. Leave it off images near the top, and add fetchpriority="high" to the main hero image.
  3. Always set width and height on images and iframes.
  4. Serve modern formats such as AVIF and WebP, in sensible sizes.
  5. Use defer for scripts, and import() for code that's only needed sometimes.
  6. Try content-visibility: auto on long pages with heavy sections.
  7. Measure the results with a tool such as PageSpeed Insights, or your browser's developer tools.

Wrapping up

Lazy loading used to mean adding a JavaScript library. Today, one HTML attribute, loading="lazy", handles images and iframes in every major browser. Combine it with proper image dimensions, high priority for the hero image, import() for optional code and content-visibility for long pages, and your pages will appear faster while using less data.

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee