Skip to content

Instantly share code, notes, and snippets.

@erikccoder
Last active August 29, 2015 14:10
Show Gist options
  • Save erikccoder/777085b98aeffbc2bdba to your computer and use it in GitHub Desktop.
Save erikccoder/777085b98aeffbc2bdba to your computer and use it in GitHub Desktop.
imageExists
// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
$.get(image_url)
.done(function() {
// Do something now you know the image exists.
}).fail(function() {
// Image doesn't exist - do something else.
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment