Is there a way to determine if a image path leads to an actual image, Ie, detect when an image fails to load in Javascript.
For a web app, I am parsing a xml file and dynamically creating HTML images from a list of image paths. Some image paths may no longer exist on the server so I want to fail gracefully by detecting which images fail to load and deleting that HTML img element.
Note JQuery solutions wont be able to be used(the boss doesn't want to use JQuery, yes I know dont get me started). I know of a way in JQuery to detect when an image is loaded, but not whether it failed.
My code to create img elements but how can I detect if the img path leads to a failed to load image?
var imgObj = new Image(); // document.createElement("img");
imgObj.src = src;
You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.
And my sympathies for the jQuery-resistant boss!
Here's a function I wrote for another answer: Javascript Image Url Verify. I don't know if it's exactly what you need, but it uses the various techniques that you would use which include handlers for
onload
,onerror
,onabort
and a general timeout.Because image loading is asynchronous, you call this function with your image and then it calls your callback sometime later with the result.
This:
just like below:
The answer is nice, but it introduces one problem. Whenever you assign
onload
oronerror
directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.Let me rewrite the answer a little bit.
Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.