Deliver optimized, art-directed images capable of changing aspect ratio based on a breakpoint.
Resize your browser below 900px to see the image change.
The picture tag is used, as opposed to the image tag with srcset and size attributes, due to the need of the image to change aspect ratios. While WEBP is the preferred image format due to its smaller file size compared to PNG and JPG, Safari doesn't support WEBP. So we have to first define a JPG or PNG version of the image on the image tag, and allow the browser to upgrade to the next image format that it supports.
Now you may wonder if browsers will download both the JPG and the WEBP, resulting in a double download. It's a great question and the reason why source order is important. Sources get processed from top to bottom, and the browser will render the first format it understands that meets the specific criteria for when to render it. Meaning, if the order of medium.jpg and medium.webp were reversed in the markup—and the screen was at least 768px wide—browsers that support WEBP would render the JPG. This, of course, is not the behavior we want, so it's important that you define the fallback format after your preferred image format.
You'll also notice that native lazy loading has been added. Unfortunately, Safari doesn't support this either and will ignore it, but browsers that do support it will delay the loading of the image.
Recently, there has been a lot of discussion about adding the height and width attributes to the image tag, to prevent reflow of the page when the image loads. While this is recommended and does work when using images that all have the same aspect ratio, it's not an option for when the images have different aspect ratios. There currently is a proposal under consideration to address this, but for now, we'll have to live with the reflow.
Lastly, don't forget to optimize your images, and provide alt text for those images that aren't purely decorative. Image optimization can be accomplished numerous ways, but is something that must be considered a requirement.
<picture> <source srcset="/img/demo/responsive-images/medium.webp" media="(min-width: 768px)" type="image/webp"> <source srcset="/img/demo/responsive-images/medium.jpg" media="(min-width: 768px)" type="image/jpeg"> <source srcset="/img/demo/responsive-images/small.webp" type="image/webp"> <img src="/img/demo/responsive-images/small.jpg" loading="lazy" alt="Description of image, if it's not decorative image."> </picture>
- IE 11