官术网_书友最值得收藏!

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.

We'll use the news article page from the last chapter as the starting point for the examples in this chapter. This file can be found at /ch3/news-start.html. To follow along with the examples, you can add code to this file. Another file, /ch3/news.html, combines most of the examples into a single page.

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:

Developer tools showing srcset image download on the desktop browser (/ch3/feature.html)

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.

If working locally, you can download the images required for the examples in this chapter at /ch3/img/ (that is, theampbook.com/ch3/img/ or github.com/ruborg/amp/tree/master/ch3/img/).
主站蜘蛛池模板: 连平县| 尚志市| 呼玛县| 鸡西市| 土默特左旗| 拉孜县| 德惠市| 崇明县| 西藏| 喜德县| 亳州市| 临泉县| 永善县| 双城市| 乡城县| 肥乡县| 江陵县| 武隆县| 修文县| 开原市| 郴州市| 浦北县| 英超| 阆中市| 资阳市| 石屏县| 交城县| 龙井市| 乡宁县| 诸暨市| 大庆市| 吉林省| 荣成市| 牡丹江市| 鄂伦春自治旗| 常德市| 金乡县| 台中市| 盘山县| 浦县| 通城县|