Skip to content

Instantly share code, notes, and snippets.

@sachintaware
Forked from draeton/checkImage.example.js
Created February 6, 2013 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintaware/4720794 to your computer and use it in GitHub Desktop.
Save sachintaware/4720794 to your computer and use it in GitHub Desktop.
// Example Use
(function () {
function success() {
console.log("success: ", this.src);
}
function failure() {
console.log("failure: ", this.src);
}
// this fails
checkImage("http://www.google.com/", success, failure);
// this succeeds
checkImage("http://www.google.com/intl/en_com/images/srpr/logo3w.png", success, failure);
})();
(function (window) {
// Stores past URLs that failed to load. Used for a quick lookup
// and because `onerror` is not triggered in some browsers
// if the response is cached.
var errors = {};
// Check the existence of an image file at `url` by creating a
// temporary Image element. The `success` callback is called
// if the image loads correctly or the image is already complete.
// The `failure` callback is called if the image fails to load
// or has failed to load in the past.
window.checkImage = function (url, success, failure) {
var img = new Image(), // the
loaded = false,
errored = false;
// Run only once, when `loaded` is false. If `success` is a
// function, it is called with `img` as the context.
img.onload = function () {
if (loaded) {
return;
}
loaded = true;
if (success && success.call) {
success.call(img);
}
};
// Run only once, when `errored` is false. If `failure` is a
// function, it is called with `img` as the context.
img.onerror = function () {
if (errored) {
return;
}
errors[url] = errored = true;
if (failure && failure.call) {
failure.call(img);
}
};
img.src = url;
// If `url` is in the `errors` object, trigger the `onerror`
// callback.
if (errors[url]) {
img.onerror.call(img);
}
// If the image is already complete (i.e. cached), trigger the
// `onload` callback.
if (img.complete) {
img.onload.call(img);
}
};
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment