简体   繁体   中英

webp fallback for img tag in html

I know the solution is <picture>

but which format is standard?

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>

Number 1 would be the standard way of doing it.

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. In your case it would only be if it supports the format in the type attribute. 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.

As stated on MDN , if the browser can't find a fitting match in the <source> s, it defaults to the <img> tag:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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