Skip to content

Instantly share code, notes, and snippets.

@markupboy
Created July 15, 2010 22:00
Show Gist options
  • Save markupboy/477597 to your computer and use it in GitHub Desktop.
Save markupboy/477597 to your computer and use it in GitHub Desktop.
// instantiate like
// var images = new imagePreloader('/path/to/image1.jpg', '/path/to/image2.jpg', ...);
var imagePreloader = function() {
var _this = this;
_this.cache = {};
_this.load = function(src, callback) {
var cacheImage = document.createElement('img');
cacheImage.src = src;
if(cacheImage.complete && callback && typeof(callback) == "function") {
callback();
return cacheImage;
}
if(callback && typeof(callback) == "function") {
cacheImage.onload = callback();
}
_this.cache[src] = cacheImage;
return cacheImage;
};
_this.loaded = function(src, callback) {
if(_this.cache[src]) {
return true;
} else {
var cacheImage = _this.load(src, callback);
if(cacheImage.complete) {
return true;
}
}
return false;
};
var argsLen = arguments.length;
if(argsLen == 2 && typeof(arguments[0]) == "string" && typeof(arguments[1]) == "function") {
_this.load(arguments[0], arguments[1]);
return;
}
for (var i = argsLen; i--;) {
if(typeof(arguments[i]) == "string")
_this.load(arguments[i]);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment