1

I have written a small JavaScript method that draws images to the DOM from a list of image urls from an S3 Bucket. In some instances these images can have broken urls. I have been searching for a the best way to test the status of these image urls with JavaScript before drawing them to the DOM. Any help would be greatly appreciated.

Mike Bonds
  • 1,020
  • 10
  • 16
  • add the code snippet you are using its important. – sabithpocker May 17 '13 at 13:16
  • If you mean broken because of a bad url, you could use regex to test for it. If not, I'm afraid you'll have to make an ajax request for every url and read the status from there. – PoeHaH May 17 '13 at 13:17
  • http://stackoverflow.com/questions/9278172/jquery-ajax-request-and-images-loading – Tom Carchrae May 17 '13 at 13:17
  • 1
    Possible duplicate: http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – tymeJV May 17 '13 at 13:17

1 Answers1

1

You could either AJAX the image and check for a 404 before you add it, or handle the image's onError:

<img src="image.png" onerror="hideImage(this);"/>

Then retrospectively remove the image from the dom in the hideImage function.

Edit: to move away from inline attributes, you could also use this on document load:

$("img").error(function () { $(this).remove(); }

Ed_
  • 18,798
  • 8
  • 45
  • 71