在 <picture> 标记中预加载响应式图像

标签 preload responsive-images

我需要预加载 <picture> 中设置的响应式图像标签:

<picture>
<source sizes="(max-width: 320px) 320px, (max-width: 480px) 480px, (max-width: 768px) 768px, (max-width: 1024px) 1024px, (max-width: 1200px) 1200px, 1500px" srcset="home-image1-bis2-1200x640.webp 1200w, home-image1-bis2-1024x546.webp 1024w, home-image1-bis2-768x410.webp 768w, home-image1-bis2-480x256.webp 480w, home-image1-bis2-320x171.webp 320w, home-image1-bis2.webp 1500w" type="image/webp">
</picture>

我找到了这个链接:https://web.dev/preload-responsive-images/ 我尝试像这样应用它:

<link rel="preload" href=home-image1-bis2-320x171.webp" as="image" type="image/webp" media="(max-width: 320px)">
<link rel="preload" href="home-image1-bis2-480x256.webp" as="image" type="image/webp" media="(min-width: 320.1px) and (max-width: 480px)">
<link rel="preload" href="home-image1-bis2-768x410.webp" as="image" type="image/webp" media="(min-width: 480.1px) and (max-width: 768px)">
<link rel="preload" href="home-image1-bis2-1024x546.webp" as="image" type="image/webp" media="(min-width: 768.1px) and (max-width: 1024px)">
<link rel="preload" href="home-image1-bis2-1024x546.webp" as="image" type="image/webp" media="(min-width: 1024.1px) and (max-width: 1200px)"><link rel="preload" href="home-image1-bis2.webp" as="image" type="image/webp" media="(min-width: 1200.1px)">

它似乎不起作用,控制台现在也记录此通知:

The resource home-image1-bis2-480x256.webp was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.

这对灯塔得分的 LCP 没有影响。
如何正确加载图像?

最佳答案

您可以为此用例使用 imagesrcsetimagesizes 属性:

<link 
    rel="preload"
    as="image"
    type="image/webp"
    imagesrcset="home-image1-bis2-1200x640.webp 1200w, home-image1-bis2-1024x546.webp 1024w, home-image1-bis2-768x410.webp 768w, home-image1-bis2-480x256.webp 480w, home-image1-bis2-320x171.webp 320w, home-image1-bis2.webp 1500w"
    imagesizes="(max-width: 320px) 320px, (max-width: 480px) 480px, (max-width: 768px) 768px, (max-width: 1024px) 1024px, (max-width: 1200px) 1200px, 1500px"
>

参见https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesizes

关于在 <picture> 标记中预加载响应式图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66316681/

相关文章:

css - srcset 中的 w-descriptors 必须使用 sizes 属性吗?

javascript - 如何设置相对于其自高度度而非宽度的响应式比例图像

html - 为什么 srcset 导致图像下载多次?

css - 预加载 CSS 图像

c - 如何预加载大型数组以并行缓存?

Angular: <link rel ="preload"> in index.html 用于生成的网络 worker

html - 横幅图片被剪裁,未显示为整个浏览器宽度

javascript - 预加载大型 JSON 文件

HTML srcset - 何时使用 x 描述符?