Lazy Loading for Performance
Imagine a very long page with fifty photos. A visitor opens it, reads the top, and leaves. Without lazy loading, their browser has already downloaded all fifty photos, spending data and time on forty-five that nobody saw.
Lazy loading fixes this by waiting. Images, iframes, and other heavy items far from the screen are fetched only when the visitor gets close to them. The basics of the loading attribute are covered in the earlier Image Lazy Loading lesson. This lesson takes the performance view: what to defer, what never to defer, and how to avoid the problems lazy loading can cause.
What You Will Learnβ
- What lazy loading saves, and what it can cost
- Which elements to lazy-load, and which to leave alone
- Why lazy-loading the main image hurts your Largest Contentful Paint
- How to avoid layout jumps with
widthandheight - How to lazy-load iframes, videos, and CSS backgrounds
- How to use a "click to load" pattern for heavy embeds
- How to audit a page for lazy-loading mistakes
The Big Ideaβ
For most pages, the rule is short: do not lazy-load what is on the first screen, and lazy-load most of what is not.
- HTML Code
- Scroll Lab
<!-- First screen: load it right away, and tell the browser it matters -->
<img src="/img/hero.webp" alt="A golden loaf on a wooden board"
width="1200" height="600" fetchpriority="high">
<!-- Below the first screen: wait until the visitor is close -->
<img src="/img/rye.webp" alt="Rye loaves on a rack"
width="600" height="400" loading="lazy">
<iframe src="https://video.example.com/embed"
width="560" height="315" loading="lazy"
title="The story of our bakery"></iframe>
Loaded 3 of 12 images, about 700 KB of 2050 KB.
This is a simplified model: twelve images 600 px apart, a 800 px screen, and images loading once they are within 1000 px of it. Real browsers pick their own distance, and it can depend on the connection.
In the lab, compare the three strategies at the top of the page without scrolling. Then scroll down and watch what each one has downloaded. Loading everything wastes data. Making the hero lazy delays the one image people see first. The smart option does neither.
What to Lazy-Loadβ
| Element | Lazy-load? | Why |
|---|---|---|
| The main image on the first screen | No | It is usually your Largest Contentful Paint, and should start early |
| Logo and header images | No | They are visible at once |
| Images below the first screen | Yes | Many visitors never reach them |
| Iframes (maps, videos, widgets) below the first screen | Yes | They are heavy and bring their own files |
| Images in a closed tab, menu, or accordion | Usually yes | They are not seen until opened |
| Videos below the first screen | Use preload | See below |
| CSS background images | Use a script | The loading attribute does not apply |
If you are not sure whether something is on the first screen, check it at a few common screen sizes. A tall hero on a phone may push the second image off the screen, while on a wide monitor it might be visible at once.
Lazy Loading Is Not Freeβ
Lazy loading can cause its own problems if you are careless:
- Delay for what is visible. A lazy image waits for the browser to lay out the page before it starts. For the main image, that is a delay you do not want.
- Layout jumps. An image with no
widthandheighthas no size until it arrives, so the page shifts as the visitor scrolls. This hurts your Cumulative Layout Shift (CLS). - Blank spaces. If the visitor scrolls fast on a slow connection, they may reach an image before it has loaded. Browsers start the download before the image reaches the screen, but on a slow network it may still show a gap.
- Hidden content. Images that are never shown, such as those in
display: noneareas, may never load.
The fixes are simple: leave the first-screen images alone, always give images and iframes a width and height, and use a placeholder colour or a reserved shape so the gap looks intentional.
Reserve the Spaceβ
An image that has width and height lets the browser reserve the right room before it arrives. CSS can still make it fit its container:
img {
max-width: 100%;
height: auto;
}
For a box with no image yet, such as an embed or a CSS background, you can reserve space with aspect-ratio:
.video-box {
aspect-ratio: 16 / 9;
background: #eee;
}
Videos and Iframesβ
Native lazy loading works for img and iframe. A video element has no loading attribute, but you can control how much it downloads up front:
<video src="/media/story.mp4" controls preload="none"
poster="/img/story-poster.jpg" width="560" height="315"></video>
preload="none"downloads no video data until the visitor plays it.preload="metadata"fetches just enough to show the length and first frame.- A
posterimage shows something useful while the video waits.
Click to Load: A Kind Way to Embedβ
A video or map embed can pull in dozens of files, and may contact third-party servers, before anyone has pressed play. A "click to load" pattern (sometimes called a facade) shows a simple picture and button, and loads the real embed only when the visitor asks:
<button type="button" class="video-facade" data-embed="https://video.example.com/embed/123">
<img src="/img/story-poster.jpg" alt="" width="560" height="315" loading="lazy">
<span>Play the video</span>
</button>
document.querySelectorAll(".video-facade").forEach(function (btn) {
btn.addEventListener("click", function () {
const frame = document.createElement("iframe");
frame.src = btn.dataset.embed;
frame.width = 560;
frame.height = 315;
frame.title = "The story of our bakery";
frame.allow = "autoplay; fullscreen";
btn.replaceWith(frame);
}, { once: true });
});
This saves data and time for everyone who does not press play, and it is also good for privacy, because no third party is contacted until the visitor chooses. Make sure the button has an accessible name (here, the visible text does the job).
Lazy-Loading CSS Backgroundsβ
The loading attribute does not apply to CSS backgrounds. A small script using IntersectionObserver can add the image when the element gets near the screen:
<div class="lazy-bg" data-bg="/img/banner.webp"></div>
const io = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
entry.target.style.backgroundImage = "url(" + entry.target.dataset.bg + ")";
observer.unobserve(entry.target);
});
}, { rootMargin: "300px" });
document.querySelectorAll(".lazy-bg").forEach(function (el) { io.observe(el); });
The rootMargin starts the load a little before the element is on screen. This approach needs JavaScript, so choose it only for decorative backgrounds, and give the element a plain background colour as a fallback. For important images, a real img with loading="lazy" is simpler and more robust.
A Note on Search Enginesβ
Search engines generally handle the native loading="lazy" attribute well, because the image has a real src in the HTML. Patterns that leave the src empty and fill it in with JavaScript are riskier, since the crawler needs to run your script to see the image. Prefer native lazy loading, and check any important images with a tool such as Search Console's URL inspection. The HTML SEO Basics lesson has more.
Audit a Pageβ
Load the messy page below and fix each problem, one at a time.
Loading the checker...
Checking in DevToolsβ
- Open DevTools, then Network, and filter by Img.
- Reload without scrolling. Only images near the first screen should load.
- Scroll down slowly. New images should appear in the list just before they reach the screen.
- Look at the first screen's main image. It should start early and not be lazy.
- Throttle the network to a slow setting, and scroll quickly. Do gaps appear? If so, consider a larger margin or a placeholder.
- Run Lighthouse and check your LCP and CLS before and after.
Best Practicesβ
- Never lazy-load the main image or anything on the first screen.
- Lazy-load images and iframes below the first screen.
- Always give
widthandheight. - Use native
loading="lazy"first, and a script only where it cannot work. - Use
preload="none"or"metadata"and aposterfor videos below the first screen. - Use click-to-load for heavy embeds.
- Keep a real
srcin the HTML, so the page works without JavaScript. - Test with a slow connection and a fast scroll.
Quick Checklistβ
- The first-screen images are not lazy
- Later images and iframes use
loading="lazy" - Every image and iframe has
widthandheight - Images keep a real
srcin the HTML - Videos use
preloadand aposter - Heavy embeds load on click, if they are not essential
- DevTools shows only nearby images loading on a fresh load
- LCP and CLS are checked before and after
Security and Privacy Notesβ
- Lazy loading is not a privacy tool by itself. A lazy third-party iframe still contacts its host when the visitor scrolls near it, and visitors may scroll without choosing to interact. For services that need consent, or that track visitors, use a click-to-load pattern, or wait for consent before adding the embed. This is not legal advice, so check the rules that apply to you.
- Trust what you embed. An iframe runs another site inside yours. Use only hosts you trust, and consider the
sandboxattribute for untrusted content. - Do not put private data in image URLs. Lazy-loaded URLs are visible in the page source and may be logged.
- Do not hide important content behind a script. If the lazy-loading script fails or is blocked, the page should still show its important images.
Global Audience Notesβ
- Lazy loading saves the most for people on limited data. On pay-as-you-go plans, every skipped image is money saved.
- Slow networks make gaps more obvious. Use placeholders and a modest margin so scrolling feels smooth.
- Fast scrollers and older devices may reach images before they load. Test on a modest phone.
- Layouts that run right to left behave the same way, since lazy loading depends on vertical position. Check that placeholders and reserved space look right in your own language.
- Images carry meaning. Always give lazy images useful
alttext, so they are understood even before or without loading.
Common Mistakes to Avoidβ
- Lazy-loading the main image.
- Lazy images with no
widthandheight. - Every image lazy, including the logo.
- An empty
srcthat depends on JavaScript. - Writing
loading="true"or another value that is notlazyoreager. - Lazy-loading hidden images and expecting them to load when shown.
- Heavy embeds loading straight away when a facade would do.
- Videos with no
preloadand noposter. - Testing only on a fast connection, and missing the gaps.
- Not checking LCP and CLS after the change.
Practice Timeβ
- In the Scroll Lab, at the top of the page, two strategies download the same amount. Which two, and why is one of them still worse for the visitor?
- Scroll to the bottom with each strategy. How do the totals compare?
- Load the messy page in the auditor. Fix every problem it reports.
- Open a page you built, and filter the Network panel by Img. Which images load before you scroll?
- Add
loading="lazy"to the ones below the first screen, and reload. - Add
widthandheightto every image, and check there is no jump. - Replace one iframe with a click-to-load button.
- Bonus: run Lighthouse before and after, and compare LCP and CLS.
Quick Recapβ
Click a question to check your answer.
1. What does lazy loading do?
It delays loading images and iframes until the visitor gets near them, saving data and speeding up the first load.
2. Which images should never be lazy-loaded?
The main image and anything else on the first screen. Lazy loading delays them, which usually makes Largest Contentful Paint worse.
3. How do you avoid layout jumps with lazy images?
Give every image and iframe a width and height, so the browser reserves the space. For other boxes, use aspect-ratio.
4. How do you lazy-load a video?
Videos have no loading attribute. Use preload="none" or "metadata" with a poster image, or a click-to-load pattern.
5. What about CSS background images?
The loading attribute does not apply. Use IntersectionObserver in a small script, and keep the approach for decorative images.
6. Why is click-to-load good for privacy?
No third-party server is contacted until the visitor chooses to play or load the embed.
Key Takeawaysβ
- Lazy loading waits. It spares the visitor from downloading what they may never see.
- First screen: never lazy. Below it: usually lazy.
- Always reserve space with
width,height, oraspect-ratio. - Prefer native
loading="lazy", with a realsrc. - Videos use
preloadandposter. Heavy embeds can load on click. - Use a script only where native lazy loading cannot work.
- Test on slow networks and check LCP and CLS.
Next up: Script Loading, where you will learn how the browser fetches and runs your JavaScript, and how to stop it blocking the page.