HTTP, TLS & Web Performance

Lazy Loading Done Right

Defer off-screen images, iframes and scripts without slowing your main content or making the page jump around.

Key takeaways

  • Add loading="lazy" to images and iframes that start off screen, and leave it off anything visible when the page first appears.
  • Never lazy load your largest above-the-fold image, because doing so usually makes the main content appear later.
  • Always give images dimensions so that late arrivals don't shove the page around.
  • Heavy third-party embeds are often best replaced with a lightweight placeholder that loads the real thing on click.
  • Code can be deferred too, using dynamic imports for features that many visitors never use.

Lazy loading means holding back a resource until the visitor is likely to need it. Done right, it applies to things below the fold, the part of the page you have to scroll to reach, and leaves everything visible on arrival to load as fast as possible. For images and iframes, the browser can do this for you with one attribute: loading="lazy".

The common mistake is applying it to everything. That delays the very picture people came to see. The rest of this guide shows where to use it, where not to, and how to avoid the side effects.

Why deferring helps

A browser has a limited amount of bandwidth and processing time during the first moments of a visit. If it spends them fetching twenty pictures from the bottom of an article, the stylesheet, fonts and headline image have to compete for the same connection.

Deferring those requests shortens the queue. It also saves data for visitors who never scroll that far, which matters on metered mobile plans, and it reduces your own delivery traffic.

The trade-off is that a deferred resource starts later. If the visitor scrolls quickly or the connection is slow, they may see an empty box for a moment. Good lazy loading starts the fetch a little before the item scrolls into view.

Native lazy loading for images and iframes

Browsers support the attribute directly:

<img src="diagram.webp" width="800" height="450" loading="lazy" alt="Network diagram">
<iframe src="https://example.com/map" width="800" height="450"
        loading="lazy" title="Location map"></iframe>

The browser decides how close to the viewport an item must be before it fetches it. That distance isn't fixed by the standard, differs between browsers and can depend on connection speed. Browsers also skip lazy deferral when scripting is disabled, as a guard against the behavior being used to track scroll position.

The default value is eager, which loads normally. There's no need to write it.

What should never be lazy

The Largest Contentful Paint element, usually a hero image or headline block, is the thing your visitor is waiting for. It's one of the Core Web Vitals. If you lazy load it, the browser has to work out the layout before it knows the image is visible, and only then requests it.

Instead, mark it as important:

<img src="hero.webp" width="1200" height="600" fetchpriority="high" alt="Harbor at sunrise">

fetchpriority="high" is a hint, and browsers that don't understand it simply ignore it. Use it on one image, perhaps two. Marking everything as high priority is the same as marking nothing.

Should this resource be lazy?
Is it visible when the page first appears? YES Load it eagerly. Prioritize it if it is the main image. 1 NO Is it an image or iframe further down the page? YES Add loading=lazy and set its dimensions. 2 NO Is it a heavy embed such as a video player or map? YES Show a light placeholder and load it on click. 3 NO Is it code for a feature used only sometimes? YES Import it dynamically when the feature is opened. 4 NO Leave it alone Small, essential items gain nothing from deferral. Is it visible when the page first appears? 1 IF YES Load it eagerly. Prioritize it if it is the main image. NO Is it an image or iframe further down the page? 2 IF YES Add loading=lazy and set its dimensions. NO Is it a heavy embed such as a video player or map? 3 IF YES Show a light placeholder and load it on click. NO Is it code for a feature used only sometimes? 4 IF YES Import it dynamically when the feature is opened. NO Leave it alone Small, essential items gain nothing from deferral.

"Above the fold" varies with screen size. An image that sits off screen on a phone may be visible on a large monitor. When unsure about the first few images, load them eagerly and lazy load the rest.

Reserve space to prevent jumping

If the browser doesn't know an image's shape, it gives it no height until the file arrives, then pushes the text down. This is layout shift, and lazy loading makes it more noticeable because arrivals happen while people are reading.

Set width and height to the image's intrinsic proportions and let CSS scale it:

img { max-width: 100%; height: auto; }

Modern browsers use the attributes to compute the aspect ratio before the download. For containers filled by script, reserve room with the CSS aspect-ratio property or a min-height. An aspect ratio calculator helps when you're working backwards from a design.

When you need custom behavior

Native loading doesn't cover CSS background images, custom widgets or "load more" lists. For those, the Intersection Observer API reports when an element approaches the viewport without you having to run code on every scroll event.

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    entry.target.classList.add('is-loaded');
    observer.unobserve(entry.target);
  }
}, { rootMargin: '300px' });

document.querySelectorAll('.lazy-bg').forEach((el) => observer.observe(el));

Your CSS then applies the background image only to .lazy-bg.is-loaded. The rootMargin value starts the work 300 pixels early; tune it to your content.

How a deferred image arrives
Visitor Browser Server Request page 1 HTML with lazy images 2 Show visible content 3 Scroll toward an image 4 Request that image 5 Starts before it is on screen Image data 6 Visitor Browser Server Request page 1 HTML with lazy images 2 Show visible content 3 Scroll toward an image 4 Request that image 5 Starts before it is on screen Image data 6

Avoid the old pattern of putting the real address only in a data-src attribute for every image. If the script fails, nothing appears, and some crawlers and tools won't see the pictures. Native lazy loading keeps a real src in the HTML.

Embeds, video and code

Third-party video players, social posts, chat widgets and interactive maps can pull in large amounts of script. A facade is a static preview, such as a thumbnail with a play button, that swaps in the real embed when clicked. Make it a real button with a text label so keyboard and screen reader users can activate it.

For your own video, preload="none" or preload="metadata" on the video element asks the browser not to download the whole file in advance. Supply a poster image so there's something to see. Autoplaying video will be fetched regardless.

JavaScript can be split so that rarely used features load on demand:

button.addEventListener('click', async () => {
  const { openEditor } = await import('./editor.js');
  openEditor();
});

Handle the failure case, since a dropped connection will reject the import. If the first click feels slow, start the import when the pointer hovers over the button or when the browser is idle.

CSS offers a related tool. content-visibility: auto lets the browser skip rendering work for off-screen sections. Pair it with contain-intrinsic-size to give each skipped section an estimated size, or the scrollbar will lurch.

Loading ahead on purpose

Deferral has a mirror image: fetching something early because it's very likely to be needed. In a photo gallery, you might request the next picture once the current one has loaded. On a long product list, you can start fetching the next page of results when the visitor is a screen or two from the end, so the content is ready when they arrive.

Keep this modest. Guessing wrong spends the visitor's data on things they never see. Look for signals that suggest restraint, such as the Save-Data request header, which some browsers send when the user has asked to reduce data use. Support varies, so treat its absence as unknown.

Placeholders help the waiting period feel intentional. A solid color taken from the image, or a tiny blurred preview, fills the reserved box until the full file arrives. Make sure the placeholder is much smaller than what it stands in for, and don't add an elaborate animation that costs more processing than the image itself. For meaningful pictures, the alt text should be present from the start so assistive technology doesn't depend on the download.

What can go wrong

  • Infinite scroll with no way out. Footer links become unreachable and the back button loses the visitor's place. Offer a "load more" button or paginated URLs.
  • Printing and saving. Deferred images may be missing from a printout if they were never fetched. Test the print view if your readers use it.
  • Anchor jumps. Linking to a section far down the page can land in the wrong spot if unsized content above loads afterwards.
  • Lazy inside carousels. Hidden slides may or may not be considered near the viewport. Check what actually gets requested.
  • Double systems. A plugin that adds script-based lazy loading on top of the native attribute can delay images twice.

How to verify it works

Open your browser's developer tools, go to the Network panel, disable the cache and reload without scrolling. Off-screen images should be absent from the list and appear as you scroll. Then throttle the connection to a slow profile and scroll at a normal pace to see whether empty boxes bother you. If you haven't used these panels before, start with browser developer tools.

Also run a lab test and compare the main content timing and layout shift before and after. The method is described in how to run a performance audit.

Lazy loading postpones bytes but doesn't shrink them. Combine it with efficient image formats and keep an eye on render-blocking resources, which delay the first paint no matter how many pictures you defer.

Common questions

Does lazy loading hurt search indexing?

Native lazy loading with a normal src keeps the address in the page, which crawlers can read. Content that only appears after a user scrolls or clicks, through custom script, is riskier. Provide ordinary links to paginated pages for anything you want found.

Should small pages bother?

If your page has two images and no embeds, there's little to gain. The effort pays off on long articles, galleries, product listings and pages carrying third-party widgets.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic