Sometimes, we want to detect when an image fails to load in JavaScript.
In this article, we’ll look at how to detect when an image fails to load in JavaScript.
How to detect when an image fails to load in JavaScript?
To detect when an image fails to load in JavaScript, we can listen for the img element’s error event.
For instance, we write
const imageFound = () => {
alert("That image is found and loaded");
};
const imageNotFound = () => {
alert("That image was not found.");
};
const img = new Image();
img.onload = imageFound;
img.onerror = imageNotFound;
img.src = "http://foo.com/bar.jpg";
to create an img element with Image.
Then we set img.onerror to the imageNotFound function.
imageNotFound runs when the img with the img.src URL fails to load.
Conclusion
To detect when an image fails to load in JavaScript, we can listen for the img element’s error event.