html 中 img 标签的 webp 回退

webp fallback for img tag in html

我知道解决方案是 <picture>

但哪种格式是标准的?

1.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <img src="pic.jpg"  alt="test">
 </picture>

2.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <img src="pic.jpg"  alt="test" type="image/jpeg">
 </picture>

3.

 <picture>
   <source type="image/webp" srcset="pic.webp">
   <source type="image/jpeg" srcset="pic.jpg">
   <img src="pic.jpg"  alt="test">
 </picture>

1 号是标准的做法。

当使用 <picture> 元素时,浏览器会查看每个 <source> 元素 - 从顶部开始 - 以找到最适合当前场景的图像。在您的情况下,只有它支持 type 属性中的格式。但如果您在 srcset 列表中添加 2x 或 3x 版本,它也可以在 media 属性中查找媒体查询或用户屏幕的像素密度等内容。

MDN 所述,如果浏览器在 <source> 中找不到合适的匹配项,则默认使用 <img> 标签:

The <img> element serves two purposes:

It describes the size and other attributes of the image and its presentation. It provides a fallback in case none of the offered <source> elements are able to provide a usable image.

因此您示例中的 JPEG 也不需要 <source>,因为如果使用 <source> 中的 none,它将被选中。