How to check if <img> is not 404 and shown correctly?

in Script development
Subscribe to How to check if <img> is not 404 and shown correctly? 5 posts, 3 voices



OwynTyler Scriptwright
ChromeWindows

Is it possible? Cuz on a website when I need to replace image sources (lower quality version to higher) some type of images doesn't match replacing and shown as empty images, can I check it (and if so replace those back) ?

 
w35l3y Scriptwright
FirefoxWindows

image.addEventListener("load", function (e) {
    alert("SUCCESS");
}, false);

image.addEventListener("error", function (e) {
    alert("ERROR");
}, false);

 
Jefferson Scher Scriptwright
FirefoxWindows

If you can't use the above code to monitor the loading, perhaps...

Firefox has long supported imageObject.naturalHeight and imageObject.naturalWidth properties which are valid if the image loaded successfully. (Safari and Chrome also have this, but I don't know when support began. IE9 has them, too, but older versions of IE do not.)

 
OwynTyler Scriptwright
ChromeWindows

sounds good, I used 2nd method in my other work, but can you do the same or just check if just _a link_ to image is valid and won't give 404?

 
Jefferson Scher Scriptwright
FirefoxWindows

I don't see how you can know whether a server will return a 404 without sending a request.