4

I'm trying to implement retina (2x) images across my website. Our pages are built from templates where we just use standard inline images:

<img src="path/to/image.png" />

I thought I could be clever and update this with srcset:

<img src="path/to/image.png" srcset="path/to/image@2x.png 2x" />

However, we don't have 2x variants of many of these images yet.

So I tested the srcset attribute with a non-existent image specified as the 2x resource, thinking that since it wasn't available, the browser would just display the standard image as specified in the src. Instead, it tried to load the missing 2x resource and displayed a broken image on the page.

Is there any way to have the browser display the 1x image as a fallback if the 2x image doesn't exist? Otherwise, I can't update the templates until every single image has a 2x variant, or we'll end up with broken images all over the place.

daGUY
  • 27,055
  • 29
  • 75
  • 119
  • You can try `onerror` event of image to load fallback image.If you don't want scripts then [this](http://stackoverflow.com/questions/980855/inputting-a-default-image-in-case-the-src-attribute-of-an-html-img-is-not-vali) is also a good solution – Vinay Jan 14 '17 at 01:50
  • isn't it possible to just not use `srcset` for images you don't have? Why would you want broken link in your HTML in the first place? – Mirko Vukušić Jan 14 '17 at 01:54
  • No, because there's a ton of pages all generated from this same template. If I want to use `srcset` on one page, I have to use it for all of them. – daGUY Jan 14 '17 at 02:06
  • How did you end up dealing with it? – pilau Jul 02 '19 at 10:02

1 Answers1

2

The answer is no. All images in the srcset must exist. Otherwise, you'll end up with broken images all over the place.

Saying that, if you use onerror, you can have one fallback image:

<img src="path/to/image.png" srcset="path/to/image@2x.png 2x" onerror="this.onerror=null;this.src='path/to/image.png'" />
Paul Chris Jones
  • 2,646
  • 1
  • 23
  • 21