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

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/).
主站蜘蛛池模板: 望江县| 桓仁| 灵璧县| 肇州县| 甘洛县| 汉寿县| 香港 | 团风县| 印江| 噶尔县| 茌平县| 剑川县| 丰镇市| 梧州市| 阜康市| 福鼎市| 金湖县| 北票市| 永丰县| 武夷山市| 阳信县| 天门市| 淄博市| 兖州市| 桑植县| 涪陵区| 洪江市| 安徽省| 万年县| 义乌市| 阳曲县| 乌鲁木齐市| 天等县| 武冈市| 涡阳县| 乐都县| 海丰县| 竹山县| 大庆市| 遂溪县| 扶余县|