- AMP:Building Accelerated Mobile Pages
- Ruadhan O'Donoghue
- 317字
- 2021-07-08 10:04:06
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.
- Advanced Quantitative Finance with C++
- Raspberry Pi Networking Cookbook(Second Edition)
- R語言游戲數據分析與挖掘
- 營銷數據科學:用R和Python進行預測分析的建模技術
- 大學計算機基礎(第2版)(微課版)
- 小程序開發原理與實戰
- Mastering Apache Maven 3
- Instant Lucene.NET
- Troubleshooting Citrix XenApp?
- 大學計算機基礎
- Python物理建模初學者指南(第2版)
- C#網絡編程高級篇之網頁游戲輔助程序設計
- JavaScript設計模式與開發實踐
- Instant AppFog
- 語義Web編程