
Using srcset to optimize image loading
With srcset, we can specify different images to use at different viewport widths. The browser will then choose the most appropriate image for the user's device by picking the smallest image that is as large as, or larger than, the viewport width.
Building on our news article example from the last chapter, let's replace the amp-img feature image with the following (full code at /ch3/feature.html):
<amp-img src="img/feature.jpg"
srcset="img/feature-1200.jpg 1200w,
img/feature-lrg.jpg 1080w,
img/feature-med.jpg 768w,
img/feature.jpg 320w"
width="768"
height="305"
layout="responsive"
alt="Feature image">
</amp-img>
The srcset attribute takes a comma-separated list of alternative images that can be used, as well as the width of each. For example, in the preceding code, feature-lrg.jpg is the filename, and 1080w tells the browser that this image has a width of 1080 pixels.
Save this page on your web server and load it in your desktop browser (or visit theampbook.com/ch3/feature.html) and look at the Network tab of the developer tools:

Depending on the width of your browser viewport, you should see which image was actually downloaded. Was it the one you were expecting? As you resize the browser, you will see alternative images being fetched whenever there is a better match for the viewport size.
Note that we are still using layout="responsive" with our different srcset images. This means that no matter what image is chosen by the browser, AMP will still resize this image to fill the viewport so that all viewport sizes will have a similar experience.