Sometimes, we want to check if an image exists on the server with JavaScript.
In this article, we’ll look at how to check if an image exists on the server with JavaScript.
Listen to the Image error Event
We can listen to the error event trigger by the image element when the image fails to load to check whether there’s any errors trigger from loading the image from the server.
For instance, we can write:
const image = new Image();
image.onload = () => {
document.body.appendChild(image);
}
image.onerror = () => {
const err = new Image();
err.src = 'https://i.picsum.photos/id/918/200/300.jpg?hmac=1gEvFp6O-XDh4848VnlwyOIrVy8s_aJNhYyTzxN9_JA';
document.body.appendChild(err);
}
image.src = "abc";
We use the Image
constructor to create an image DOM element object.
Then we set the img.onload
property to a function that runs when the image loads successfully.
In the function, we call document.body.appendChild
to add the image to the body element.
Next, we set the img.onerror
property to a function that runs when the original image fails to load.
In the function, we create a new Image
instance and set the src
to an image that we load in case the original one fails to load.
Finally, we set image.src
to an invalid URL so the onerror
method runs and loads the fallback image.
Conclusion
We can listen to the error
event of an image to see when the original image we’re loading fails to load.