Files in different formats are chosen with the source type in picture; files at different resolutions are chosen with srcset and sizes. Setting width and height and adding lazy loading also reduces layout shift and unnecessary downloads.
Even if you compress a file well, serving a file that doesn't fit the screen is wasteful. There's no reason to send a 2000px-wide photo to a phone that's 360px wide. The web solves this along two axes. Format is <picture> + type; resolution is srcset + sizes.
In srcset, list several sizes of the same picture in the form width + w, and in sizes, write the width this image will take up on screen. The browser looks at both together with the screen's pixel ratio (DPR) and picks a suitable candidate. Which candidate to pick is up to the browser and is not a rule guaranteed by the spec, so don't use it to force an exact choice.
<img
src="photo-800.jpg"
srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width="800" height="533"
alt="Riverside scenery"
loading="lazy" decoding="async"><picture>
<source type="image/avif"
srcset="photo-480.avif 480w, photo-800.avif 800w, photo-1600.avif 1600w"
sizes="(max-width: 600px) 100vw, 800px">
<source type="image/webp"
srcset="photo-480.webp 480w, photo-800.webp 800w, photo-1600.webp 1600w"
sizes="(max-width: 600px) 100vw, 800px">
<img src="photo-800.jpg"
srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width="800" height="533" alt="Riverside scenery"
loading="lazy" decoding="async">
</picture><img>. <picture> only handles the selection rules.image/avif, WebP is image/webp, and JPEG XL is image/jxl. The browser skips a source whose type it can't interpret.alt="".Slicing sizes too finely increases the number of files to produce and cache. First check the maximum width that actually appears on screen. If the content width is 800px, 1600px is for high-resolution (2x) screens and almost nothing beyond that is needed. Starting with three or four representative widths is easier to manage. Tools like the Next.js image component can do this for you, but you still have to check for yourself which attributes get output.
An img/source attribute that lists several resolution (or pixel-ratio) candidates for the same image.
An attribute that tells the browser the width the image will take up on screen. Used to choose among srcset's w candidates.
Surrounding content getting pushed around because an image loads late. Reduced by reserving space with width and height.
Which describes the role of <img> inside <picture>?
What is the main reason to set the width and height attributes on <img>?