Posted on: February 22, 2023|Amrish Kushwaha

Use a fallback image when the image is failed to load

Use a fallback image when the image is failed to load

If images don't load, it is a nightmare for you as a developer.

Sometimes images don't load and it creates a very bad user experience. The reason for not loading the images can be a range of issues - the network is slow and the image is large (large MBs) in file size, so the browser couldn't download it. We could solve this big file issue by compressing the image and providing less size image.

Another reason for not loading the image could be - accidentally providing the wrong image source where there is no image at all. This can be solved by - providing a correct image source. If the website or app is really big, we can solve this loading issue by providing a fallback image if the main image fails to load.

Another reason for not loading the image could be - if you are using images from a source where you don't have complete control such as from a third-party website or application available on the internet etc and they remove that images, then you will be in a nightmare. This issue can also be solved using a common fallback image.

We can solve most of not loading image issues by providing a fallback image. A fallback image would be really helpful in case of if there is a list of cards on which we would have to show images - such as a list of blog posts' cards.

In this article, we are going to explore ways of implementing the callback image in the different-different scenarios:

Fallback image in HTML

We can solve the image not loaded issue in HTML explicitly by setting the image src attribute in the onerror method of img element.

Check this code below:

<img
src="images/sample2.jpg"
alt="Sample"
height="300"
width="500"
onerror="this.onerror=null;this.src='./images/sample.jpg';"
/>

As you can see in the above code, we are setting src property in case of the error in loading the image.

Fallback image in Vanilla JS

We can also solve the image not loaded issue dynamically.

Check the code below:

html

<div class="box"></box>

javascript

function appendImage(target, options) {
const img = new Image()
img.src = options.src
img.alt = options.alt
img.onerror = function (e) {
e.stopPropagation()
this.src = `./images/sample2.jpg`
}
target.appendChild(img)
}
const box = document.getElementsByClassName("box")
appendImage(box[0], { src: "./images/sample.jpg", alt: "Sample" })

As you can see in the above code when we are creating an image dynamically. If there are images not loaded related errors happen, then onerror method will set the fallback image.

Fallback image in React

Nowadays, frontend development mostly being done in React. So in this article, we will see how we can solve the image not loaded issue in React also.

Check this code below:

import React, { useState } from "react"
function App() {
const [imgSrc, setImgSrc] = useState("./images/image1.png")
const handleError = e => {
e.stopPropagation()
setImgSrc("./images/fallback.png")
}
return (
<div className="container">
<div className="box">
<img src={imgSrc} alt="Sample" onError={handleError} />
</div>
</div>
)
}
export default App

as you can see in the above code when the image is not loaded related error is thrown, then the handleError method set a fallback image for it.

Alternatively, we can image an Image component which will support the fallback image natively.

Check the below code:

Image component

import { useState } from "react"
const Image = props => {
const { src, ...rest } = props
const [SRC, setSrc] = useState(image)
const fallbackImageSrc = "../images/fallback.png"
const handleError = () => {
setSrc(fallbackImageSrc)
}
return <img src={SRC} onError={handleError} {...rest} />
}
export default Image

Usage

import Image from "./components/Image"
const Component1 = () => {
return <Image src="./images/image1.png" alt="Image 1" />
}
export default Component1

As you can see in the above code, we have created a generic Image component which can be used in the place of img tag. The Image component natively supports fallback image functionality.

That's all.

Thanks for reading the article. Keep coding and keep solving problems.

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Related category articles: