Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  28] [ 7]  / answers: 1 / hits: 162096  / 12 Years ago, thu, march 22, 2012, 12:00:00

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;

More From » image

 Answers
5

You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.



function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}

function imageFound() {
alert('That image is found and loaded');
}

function imageNotFound() {
alert('That image was not found.');
}

testImage(http://foo.com/bar.jpg);


And my sympathies for the jQuery-resistant boss!


[#86683] Tuesday, March 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
brodyfrancisi questions
;