If you are adding images in your web-pages,then there is a possibility that image may not load, local or remote images, so in that cases we render default image or fallback image in HTML, so in this article, I have mentioned how we can add Fallback image in HTML.

Using only HTML

If you want pure HTML based solution to add fallback image, then you can simply wrap, img tag with object tag.

If object HTML tag src is not loaded properly then img tag image is show to user.

Sample HTML code would be as below

<object data="https://some-url-doesnt-exists/not-existing-image.jpeg" type="image/jpg">
  <img src="fallback-image.jpeg" />

Let's take a look an example

<object data="https://some-image-url-which-doesnt-exists.jpeg" type="image/jpg">
  <img src="https://picsum.photos/250" alt="" />

Take a look at fiddle here:


In the above HTML code we are using object tag, which can be used to load images, PDF, other web-pages content etc.

Using Javascript in HTML

If you don't want to use object HTML tag as shown above, then you can also simply using inline-javascript to load fallback HTML image.

Here is how you can do it.

<img src="yourPrimaryImage.jpg" onerror="this.src='fallback-image.jpg';this.onerror='';">

So as you can see in the above HTML, we are using onerror img attribute and adding fallback image if main src image is not loaded.

Using CSS

You can simply use image as background image for div, and if one image doesn't image then second image will be displayed to user.




     background-image: url('http://placehol/1000x1000'), url('https://picsum.photos/250');
     background-size: 100%;

In the above CSS Code, image with url 'http://placehol/1000x1000' will not be loaded so second image is loaded.


Here is fiddle:


That's it.

You may also like to read:

Creating Read More / Less buttons using jQuery & Javascript

HTML Comment Multiple lines (Block comments)

Change PNG image color using CSS

Rotate image using HTML and CSS

Custom Checkbox and Custom Radio buttons in HTML / CSS

Add text on mouseover or hover element in HTML

Responsive center image using pure CSS or Bootstrap