Native HTML Images and Lazy Loading
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. The browser already knows how to pick a file, delay a download and avoid layout jumps, if the markup gives it the information. This page lists the attributes that matter. The server side (which variants to produce and which URLs to return) is in responsive images and thumbnails, and the general loading-performance background is in performance and loading. Reference pages at MDN: image format guide and responsive images.
A complete example
<picture>
<source type="image/avif"
srcset="/covers/b81f/w320.avif 320w, /covers/b81f/w640.avif 640w, /covers/b81f/w1280.avif 1280w"
sizes="(min-width: 60em) 20vw, 50vw">
<source type="image/webp"
srcset="/covers/b81f/w320.webp 320w, /covers/b81f/w640.webp 640w, /covers/b81f/w1280.webp 1280w"
sizes="(min-width: 60em) 20vw, 50vw">
<img src="/covers/b81f/w640.jpg"
srcset="/covers/b81f/w320.jpg 320w, /covers/b81f/w640.jpg 640w, /covers/b81f/w1280.jpg 1280w"
sizes="(min-width: 60em) 20vw, 50vw"
width="640" height="960"
alt="Cover of Moby-Dick"
loading="lazy" decoding="async">
</picture>
The attributes
srcsetandsizes-
srcsetlists candidate files with their intrinsic width (640w) or pixel density (2x).sizestells the browser how wide the image will be on screen at each viewport width, so it can choose before layout. Withoutsizesthe browser assumes the image is as wide as the viewport and downloads too much. Use width descriptors for fluid layouts and density descriptors for fixed-size images such as avatars. widthandheight-
Give the intrinsic size. Browsers use the ratio to reserve space before the image loads, which prevents layout shift (CLS). Set the CSS to
height: auto; max-width: 100%so the image still scales. The same applies to<video>. <picture>andtype-
The browser takes the first
<source>whosetypeit supports, so list AVIF first, WebP second, and keep the<img>as the JPEG fallback. The<img>is required, since it is the element that is rendered, and every attribute that is not about source selection (alt,width,height,loading,decoding,fetchpriority) goes on it. loading="lazy"-
Defers offscreen images until they are near the viewport. It is supported natively by current browsers, with no JavaScript. Never put it on the image that is likely the largest contentful paint (LCP) element, usually the hero image or the first cover: lazy loading delays it and worsens LCP. Everything below the first screen should be lazy. Reference: MDN loading.
decoding="async"-
Lets the browser decode the image off the main thread and display other content first. It is safe on almost every image. Use
decoding="sync"only when you need the image painted in the same frame as the surrounding content. fetchpriority-
fetchpriority="high"on the LCP image tells the browser to fetch it ahead of other images.fetchpriority="low"on carousel slides and below-the-fold images helps bandwidth go to the right place. Use it sparingly: if everything is high, nothing is. Reference: MDN fetchpriority.
How the browser picks a candidate
Understanding the selection removes most guesswork. The browser parses the markup, evaluates sizes against the current
viewport to get the slot width in CSS pixels, multiplies by the device pixel ratio (DPR) to get the needed width in device
pixels, and takes the smallest candidate that is at least that wide. If nothing is wide enough it takes the largest.
The selection is deliberately left to the browser, which may also take the network and a cached larger variant into account,
so treat the result as "at least this sharp", not as a promise. The function below mirrors the rule for the cover markup
used on this page (20vw from 60em, otherwise 50vw) and is useful to check a sizes value before you ship it:
// pick-candidate.mjs -- run with: node pick-candidate.mjs
const candidates = [320, 640, 1280]; // widths listed in srcset
const slotWidth = (viewport) => (viewport >= 60 * 16 ? viewport * 0.2 : viewport * 0.5); // sizes="(min-width: 60em) 20vw, 50vw"
export function pick(viewport, dpr) {
const needed = slotWidth(viewport) * dpr;
return candidates.find((width) => width >= needed) ?? candidates[candidates.length - 1];
}
for (const [viewport, dpr] of [[390, 3], [390, 1], [768, 2], [1440, 1], [1440, 2]]) {
console.log(`viewport ${viewport}px, DPR ${dpr}: slot ${slotWidth(viewport)}px -> ${pick(viewport, dpr)}w`);
}
Running it prints 640w for a 390 px phone at DPR 3 (a 195 px slot needs 585 device pixels), 320w for the same phone at
DPR 1, 1280w for a 768 px tablet at DPR 2, and 320w and 640w for a 1440 px desktop at DPR 1 and 2. A phone needs the
same file as a laptop here, which is exactly the saving sizes buys. Without sizes the same 1440 px desktop would
download the 1280w file for a 288 px slot, four times the pixels it needs.
Layout shift in numbers
The reserved box is computed from the width and height attributes as aspect-ratio: width / height (user agents map
the two attributes to that property), so a 640 by 960 cover in a 288 px slot reserves 288 by 432 px before a byte arrives.
CLS is the sum of the movements of visible elements, each scored as impact fraction times distance fraction, so an image
without dimensions that pushes a full-width block down by a fifth of the viewport scores roughly 0.2 on its own, well past
the 0.1 "good" threshold. When the real intrinsic size is unknown (user content), store it at upload time and return it
with the variants, as the backend does, or fall back to a CSS aspect-ratio on the container.
img { max-width: 100%; height: auto; } /* attributes give the ratio, CSS keeps it fluid */
.cover { aspect-ratio: 2 / 3; background: #e8e2d6; } /* fallback box and average colour for unknown content */
Lazy loading below the fold and for background images
loading="lazy" only applies to <img> and <iframe>. A CSS background-image is always fetched, so lazy loading it
needs an IntersectionObserver that sets the URL when the element approaches the viewport. The same helper doubles as a
fallback where you need a trigger distance different from the browser’s built-in one.
export function lazyBackgrounds(selector = '[data-bg]', rootMargin = '300px') {
const nodes = [...document.querySelectorAll(selector)];
if (!('IntersectionObserver' in window)) { // very old browsers: load everything
nodes.forEach((node) => { node.style.backgroundImage = `url("${node.dataset.bg}")`; });
return () => {};
}
const observer = new IntersectionObserver((entries, self) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const node = entry.target;
node.style.backgroundImage = `url("${node.dataset.bg}")`;
node.removeAttribute('data-bg');
self.unobserve(node); // each node is handled once
}
}, { rootMargin });
nodes.forEach((node) => observer.observe(node));
return () => observer.disconnect(); // call when the page or component goes away
}
Nodes start without a background, receive it on the first intersecting entry and are then unobserved. The rootMargin of 300px starts the download about one screen-height early, so the image is
usually decoded by the time it scrolls into view.
Measuring: LCP element and shift sources
Lab tools tell you what to fix, and the browser tells you what actually happened to a real visitor. The Performance Observer API exposes both the LCP element and each layout shift with its sources:
new PerformanceObserver((list) => {
const entry = list.getEntries().at(-1); // the latest LCP candidate
console.log('LCP', Math.round(entry.startTime), 'ms', entry.element, entry.url);
}).observe({ type: 'largest-contentful-paint', buffered: true });
new PerformanceObserver((list) => {
for (const shift of list.getEntries()) {
if (!shift.hadRecentInput) console.log('shift', shift.value.toFixed(3), shift.sources?.map((s) => s.node));
}
}).observe({ type: 'layout-shift', buffered: true });
If entry.element is a lazy-loaded <img>, remove loading="lazy" from it. If a shift source is an image, give it
dimensions. Send the same numbers to your analytics with the page type so regressions show up per template.
The LCP image
<img src="/hero/w1280.jpg" srcset="/hero/w640.jpg 640w, /hero/w1280.jpg 1280w, /hero/w1920.jpg 1920w"
sizes="100vw" width="1920" height="1080" alt="Library reading room"
fetchpriority="high" decoding="async">
The image has no loading="lazy" and has fetchpriority="high". To start the download even earlier, add a
<link rel="preload" as="image"> element to the head with the imagesrcset and imagesizes attributes.
A placeholder while the image loads
The width and height reserve an empty box. To fill it, show a BlurHash while the file downloads, see
BlurHash in the browser. A cheap CSS-only alternative is the
average colour of the image as background-color on the <img>, which the backend can return next to the BlurHash.
Video
<video controls playsinline preload="none" width="1280" height="720"
poster="/videos/42/poster-1280.avif">
<source src="/videos/42/720p.webm" type='video/webm; codecs="vp9, opus"'>
<source src="/videos/42/720p.mp4" type='video/mp4; codecs="avc1.64001f, mp4a.40.2"'>
Your browser cannot play this video.
</video>
-
posteris the image shown before playback. Generate it from a frame, see video covers and thumbnails, and serve it in the modern formats like any image (the attribute takes one URL, so choose AVIF or WebP only if you accept that older browsers show nothing, or keep a JPEG). -
preload="none"downloads nothing until the user presses play, which is right for lists of videos.preload="metadata"fetches the duration and dimensions only.preload="auto"lets the browser buffer, and wastes bandwidth when most visitors do not play. -
playsinlinekeeps playback inline on iOS rather than fullscreen. Addmutedfor autoplay, which browsers only allow for muted video. -
For several quality levels, use adaptive streaming rather than several
<source>files, see video playback and streaming.
A quick audit
-
Does every
<img>havewidth,heightandalt? -
Does every image below the first screen have
loading="lazy", and the LCP image does not? -
Does
sizesmatch the real CSS width of the slot? -
Do the
<picture>sources list AVIF and WebP with a JPEG fallback? -
Do the Lighthouse and Chrome DevTools Performance panels show the LCP element loaded early, and CLS near zero? See web.dev on LCP.
Art direction with picture
srcset with sizes chooses resolution. When the crop should change as well (a wide hero on desktop, a tight square
on a phone), use media on the <source> elements. The browser then takes the first source whose media and type both
match, and each source can carry its own srcset.
<picture>
<source media="(min-width: 60em)" srcset="/hero/wide-1280.avif 1280w, /hero/wide-1920.avif 1920w" sizes="100vw" type="image/avif">
<source media="(max-width: 59.99em)" srcset="/hero/square-480.avif 480w, /hero/square-960.avif 960w" sizes="100vw" type="image/avif">
<img src="/hero/wide-1280.jpg" width="1920" height="1080" alt="Library reading room" fetchpriority="high">
</picture>
The crops are produced by the backend, see
responsive images and thumbnails. Because the two
crops have different ratios, set width and height on the <img> to the ratio of the default crop and add a CSS
aspect-ratio override in a media query for the other, otherwise the layout shifts when the source changes.