1

Premise: I have done a lot of research on how img and source tags work, but every single article only superficially deals with the attributes of these tags.

I need to make sure that if the browser does not support the image format (eg .wepb, but it can be .raw or .nef), or the path/url is wrong, there is a correct fallback to a .jpg, then to the alt. I thought of these two solutions:

<!-- First solution -->
<img src="foo.jpg" alt="foo"
    srcset="foo.webp 1x">
<!-- Second solution -->
<picture>
    <source srcset="bar.webp">
    <img src="bar.jpg" alt="bar">
</picture>

Neither of them works, in fact if the file is not found, or if I try with unsupported extensions, there is no fallback on src, but the alt is triggered instead.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
cryfur
  • 15
  • 1
  • 5
  • Do not suppose there is such option(?) - alt should work for text browsers, disabled images, screen readers or additional info on mouse over... – Jan Apr 02 '22 at 16:25
  • 1
    Does this solve your problem? https://stackoverflow.com/questions/980855/inputting-a-default-image-in-case-the-src-attribute-of-an-html-img-is-not-vali – Suraj Sanwal Apr 02 '22 at 16:26
  • I'd say that the `onerror()` handler could be a solution https://stackoverflow.com/questions/52231187/handling-multiple-image-fallbacks-in-javascript – cheesyMan Apr 02 '22 at 16:28
  • Perhaps I naively omitted that I would like to fix the "problem" using pure HTML5 edit: I am also taking a look at the proposed solutions to understand where the root of the problem may be – cryfur Apr 02 '22 at 16:31

1 Answers1

2

Every single article only superficially deals with the attributes of img and source.

For image filetype fallbacks try the type attribute on your <source> elements:

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

In this example, the user agent will choose the first source that has a type attribute with a supported MIME type. If the user agent supports WebP images, the first source element will be chosen. If not, the img element will be chosen.

Read more in the HTML Specification

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30