webp fallback for img tag in html
Asked Answered
N

1

12

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>
Nash answered 1/1, 2021 at 10:47 Comment(0)
V
13

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.

Vilify answered 1/1, 2021 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.