Skip to content

Instantly share code, notes, and snippets.

@unknownuser88
Created January 6, 2014 15:53
Show Gist options
  • Save unknownuser88/8284833 to your computer and use it in GitHub Desktop.
Save unknownuser88/8284833 to your computer and use it in GitHub Desktop.
Using AJAX to test if the image exists
$("img").each(function() {
$.ajax({
url: $(this).attr('src'),
type: 'HEAD',
error: function() {
//image doesn't exist
console.log('ERROR');
},
success: function() {
//image exists
console.log('success');
}
});
});
/*
Output:
success
success
ERROR
success
success
*/
Non ajax
function version
/**
* Returns true if image is broken, false otherwise
* @param {jQuery} image A single image element
* @return {Boolean}
*/
isImageBroken: function(image) {
$image = $(image);
if ($image.attr('complete') == false || $image.attr('naturalWidth') == 0 || $image.attr('readyState') == 'uninitialized' || this.trim($image.attr('src')) == '') {
return true;
}
return false;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment