Skip to content

Instantly share code, notes, and snippets.

@codylindley
Created July 12, 2010 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codylindley/472928 to your computer and use it in GitHub Desktop.
Save codylindley/472928 to your computer and use it in GitHub Desktop.
/*!
* jQuery.preloadImg
* description: cache images via $.preloadImg(['src','src']) or $('img').preloadImg()
* author: Cody Lindley
*/
(function($) {
$.preloadImg = function() {
$.preloadImg.runLoader(arguments[0]);
};
$.extend($.preloadImg,{
cached:[],
temp:[],
runLoader:function() {
var argsLength = arguments[0].length;//cache length of array
for (var i = argsLength; i--;) {//load each url
var cacheImage = document.createElement('img');
cacheImage.src = arguments[0][i];
this.cached.push(cacheImage);//fix for ie bug
}
}
});
$.fn.preloadImg = function() {
if ($(this).length === 0) {return};//if the jQuery wrapper set is empty return
$.preloadImg.temp = [];
this.each(function() {//loop over the elements in the wrapper
var elmSrc = $(this).attr('src');//cache the src value
if (elmSrc === undefined || elmSrc === '') {return};//return if the src is underfined or empty string
$.preloadImg.temp.push(elmSrc);//add to temp array
});
$.preloadImg.runLoader($.preloadImg.temp);
return this;//return the jQuery object
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment