Correct way to display an img fallback

All we need is an easy explanation of the problem, so here it is.

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 -->
    <source srcset="bar.webp">
    <img src="bar.jpg" alt="bar">

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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:

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

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply