- 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.
- Expert C++
- CockroachDB權(quán)威指南
- Java 9 Programming Blueprints
- Android 9 Development Cookbook(Third Edition)
- HTML5從入門到精通 (第2版)
- Python:Deeper Insights into Machine Learning
- Building Dynamics CRM 2015 Dashboards with Power BI
- Django 5企業(yè)級(jí)Web應(yīng)用開(kāi)發(fā)實(shí)戰(zhàn)(視頻教學(xué)版)
- 零基礎(chǔ)輕松學(xué)C++:青少年趣味編程(全彩版)
- 超簡(jiǎn)單:用Python讓Excel飛起來(lái)(實(shí)戰(zhàn)150例)
- 從零學(xué)Java設(shè)計(jì)模式
- 現(xiàn)代CPU性能分析與優(yōu)化
- Node.js 6.x Blueprints
- C# 7 and .NET Core 2.0 Blueprints
- 前端Serverless:面向全棧的無(wú)服務(wù)器架構(gòu)實(shí)戰(zhàn)