Last active
August 29, 2015 14:10
-
-
Save erikccoder/777085b98aeffbc2bdba to your computer and use it in GitHub Desktop.
imageExists
This file contains 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
// 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