将<picture>响应式图片转为<link preload>的srcset+sizes实现预加载
响应式图片的等效预加载实现方案
我需要写出和以下响应式<picture>代码完全等效的预加载代码,已知<link rel="preload" as="image">可以搭配imagesizes和imagesrcset属性实现,但目前还没找到正确的写法。
原响应式图片代码:
<picture> <source media="(min-width: 1024px)" srcset="image.jpg?w=1000&h=384&auto=format&q=75 1x, image.jpg?w=1000&h=384&auto=format&q=75&dpr=2 2x"> <source media="(min-width: 708px)" srcset="image.jpg?w=700&h=256&auto=format&q=75 1x, image.jpg?w=700&h=256&auto=format&q=75&dpr=2 2x"> <source media="(min-width: 391px)" srcset="image.jpg?w=390&h=256&auto=format&q=75 1x, image.jpg?w=390&h=256&auto=format&q=75&dpr=2 2x"> <source srcset="image.jpg?w=320&h=256&auto=format&q=75&dpr=2 2x"> <img src="image.jpg?w=320&h=256&auto=format&q=75" width="400" height="256" alt="" decoding="async" fetchpriority="high"> </picture>
我自己写了一个简化版,但这个版本漏掉了<picture>里所有带&dpr=2/2x的资源;如果调整成包含这些资源,又会出现只加载2x资源的问题:
<link rel="preload" as="image" imagesrcset=" image.jpg?h=256&w=320&auto=format&q=75 320w, image.jpg?h=256&w=390&auto=format&q=75 390w, image.jpg?h=256&w=700&auto=format&q=75 700w, image.jpg?h=384&w=1000&auto=format&q=75 1000w " imagesizes=" (min-width: 1024px) 1000px, (min-width: 708px) 700px, (min-width: 391px) 390px, 320px ">
解决方案
要实现完全等效的预加载,需要把每个尺寸对应的1x和2x资源都加入imagesrcset,并通过宽度描述符(w)定义资源的实际像素宽度,让浏览器根据视口尺寸和设备像素比自动选择合适的资源。
正确的预加载代码如下:
<link rel="preload" as="image" imagesrcset=" <!-- 移动端320px容器对应的资源 --> image.jpg?w=320&h=256&auto=format&q=75 320w, image.jpg?w=320&h=256&auto=format&q=75&dpr=2 640w, <!-- 391px+视口对应的资源 --> image.jpg?w=390&h=256&auto=format&q=75 390w, image.jpg?w=390&h=256&auto=format&q=75&dpr=2 780w, <!-- 708px+视口对应的资源 --> image.jpg?w=700&h=256&auto=format&q=75 700w, image.jpg?w=700&h=256&auto=format&q=75&dpr=2 1400w, <!-- 1024px+视口对应的资源 --> image.jpg?w=1000&h=384&auto=format&q=75 1000w, image.jpg?w=1000&h=384&auto=format&q=75&dpr=2 2000w " imagesizes=" (min-width: 1024px) 1000px, (min-width: 708px) 700px, (min-width: 391px) 390px, 320px ">
关键说明
- 每个尺寸的2x资源,实际像素宽度是1x资源的2倍,因此用
640w(3202)、780w(3902)等宽度描述符定义 imagesizes完全沿用原<picture>的媒体查询逻辑,告知浏览器图片在不同视口下的显示宽度- 浏览器会结合
imagesizes计算所需像素宽度,再匹配imagesrcset中最适配的资源,同时兼顾设备像素比,行为与原<picture>完全一致,既不会遗漏2x资源,也不会强制只加载2x资源
内容的提问来源于stack exchange,提问作者retrovertigo
相关产品推荐
相关产品推荐

