Skip to content

Instantly share code, notes, and snippets.

@davetayls
Created August 19, 2011 09:17
Show Gist options
  • Save davetayls/1156419 to your computer and use it in GitHub Desktop.
Save davetayls/1156419 to your computer and use it in GitHub Desktop.
Simple image preloader
/**
Simple image preloading
Dave Taylor http://the-taylors.org
Usage:
var images = ['img.png', 'img2.png'];
window.imagePreload(images, function(errorUrls){
this == images;
});
@license The MIT License (MIT)
@preserve Copyright (c) <2011> <Dave Taylor http://the-taylors.org>
*/
/*jslint browser: true, vars: true, white: true, forin: true, indent: 4 */
/*global define*/
(function(){
'use strict';
var imagePreload = function(imageUrls, callback){
var ln = imageUrls.length, i,
images = [],
errors = [],
imagesLoaded = [],
loaded = 0,
timeout = 1000,
img;
function imageLoaded() {
if (this && this.imagePreloadTimeout) {
clearTimeout(this.imagePreloadTimeout);
}
loaded+=1;
if (loaded === ln) {
callback.call(imageUrls, errors);
}
}
function imageError() {
errors.push(this);
imageLoaded.call(this);
}
function imageTimeout(img) {
imageError.call(this);
}
function addTimeout(img, timeout){
img.imagePreloadTimeout = setTimeout(function(){
imageTimeout.call(img);
}, timeout);
}
for (i = 0; i < ln; i+=1) {
img = new Image();
img.src = imageUrls[i];
if (img.complete) {
imageLoaded.call(this);
} else {
img.onload = imageLoaded;
img.onerror = imageError;
img.onabort = imageError;
addTimeout(img, timeout);
}
images.push(img);
}
};
if (window.define && window.define.amd) {
define(function(){
return imagePreload;
});
} else {
window.imagePreload = imagePreload;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment