Created
January 6, 2014 15:53
-
-
Save unknownuser88/8284833 to your computer and use it in GitHub Desktop.
Using AJAX to test if the image exists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("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