Skip to content

Instantly share code, notes, and snippets.

@iwyg
Created April 9, 2011 14:26
Show Gist options
  • Save iwyg/911423 to your computer and use it in GitHub Desktop.
Save iwyg/911423 to your computer and use it in GitHub Desktop.
A tiny css asset preloader for the jQuery Javascript Library. See implementation.js for further instructions
$(document).ready(function(){
var cssImages = ['path/to/image1.png','path/to/image2.jpg','path/to/image3.gif'],
myElement = $('myElement');
// bind eventlistener to one jquery object
myElement.bind('assetsready',function(){
// do awesome stuff
});
// call plugin
myElement.preloadAssets( {assets : cssImages} );
});
/*
* @author thomas appel, mail(at)thomas-appel.com
*
**/
(function($){
function loadImage(src,cb){
var image = new Image();
$(image).load(function(){
cb.call(this, true);
}).error(function(){
cb.call(this, false);
});
image.src = src;
}
$.fn.preloadAssets = function(options) {
var defaults = {
assets : []
},
opts = $.extend({},defaults,options),
that = this;
return this.each(function(){
var l = opts.assets.length,j=0;
for (var i = 0;i<l;i++) {
loadImage(opts.assets[i], function(loaded){
++j;
if ( j===l ){
that.trigger('assetsready');
}
});
}
});
}
}(this.jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment