Subscribe

HTML fallback images on error

โœ๏ธ

How to show a fallback image when the image doesn't load

6 Aug, 2022 ยท 2 min read

The other day I encountered some issues with images for external sources not loading.

I saved a link to someone's Twitter profile image in this case. When the user changes this image, it doesn't auto reflect the new one.

So I decided to look into fallback images. And it's surprisingly easy.

What we want to achieve:

  • Load the image
  • If it doesn't load, show the fallback

Note: Alternatively, you could decide to remove the image

HTML on error fallback images

Let's set up a sample HTML experiment.

<img
  src="https://images.pexels.com/photos/163822/color-umbrella-red-yellow-163822.jpeg"
/>

This will load an Photo by Pixabay from Pexels (a stock image site).

This will work perfectly, but now let's try and destroy it by randomly adding some numbers to the image.

<img
  src="https://images.pexels.com/photos/163822/color-umbrella-red-yellow-00000.jpeg"
/>

With this, we get the super annoying broken image.

Broken image

So what can we do when this happens? We can use the onerror attribute on the image to set a fallback.

It works like this:

<img
  src="https://images.pexels.com/photos/163822/color-umbrella-red-yellow-00000.jpeg"
  onerror="this.onerror=null; this.src='https://images.pexels.com/photos/159868/lost-cat-tree-sign-fun-159868.jpeg'"
/>

We use the onerror to set the error to null and set the src of the image to a fallback. In our case, a photo of a missing cat.

Note: It's not a great practice to rely on external images. You ideally want to have the fallback image locally in the file system, so it's a reliable fallback.

You can see it in action in the following CodePen. The first image loads, and the second one is broken.

See the Pen HTML fallback images on error by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Submit button outside the form

4 Dec, 2022 ยท 1 min read

Submit button outside the form

Trying out native dialog modals

8 Aug, 2022 ยท 3 min read

Trying out native dialog modals

Join 1900 devs and subscribe to my newsletter