简体   繁体   English

html 中 img 标签的 webp 后备

[英]webp fallback for img tag in html

I know the solution is <picture>我知道解决方案是<picture>

but which format is standard?但哪种格式是标准的?

1. 1.

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

2. 2.

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

3. 3.

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

Number 1 would be the standard way of doing it. 1号将是这样做的标准方式。

When using the <picture> element the browser looks through each <source> element – starting from the top – to find an image that best fits the the current scenario.当使用<picture>元素时,浏览器会查看每个<source>元素 - 从顶部开始 - 以找到最适合当前场景的图像。 In your case it would only be if it supports the format in the type attribute.在您的情况下,只有它支持type属性中的格式。 But it could also look for things like media queries in the media attribute or the pixel density of the user's screen if you add 2x or 3x versions in the srcset list.但如果您在srcset列表中添加 2x 或 3x 版本,它也可以在media属性中查找媒体查询或用户屏幕的像素密度等内容。

As stated on MDN , if the browser can't find a fitting match in the <source> s, it defaults to the <img> tag:MDN所述,如果浏览器在<source>中找不到合适的匹配项,则默认为<img>标记:

The <img> element serves two purposes: <img>元素有两个用途:

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.如果所提供的<source>元素都不能提供可用的图像,它会提供一个备用方案。

So the JPEG in your example doesn't need to have a <source> as well, because it will be chosen if none of the <source> s are used.因此,您示例中的 JPEG 也不需要具有<source> ,因为如果不使用任何<source> ,它将被选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM