Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from codylindley/gist:472928
Created July 12, 2010 21:14
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 cowboy/473071 to your computer and use it in GitHub Desktop.
Save cowboy/473071 to your computer and use it in GitHub Desktop.
For Cody
/*!
* jQuery.preloadImg
* description: cache images via $.preloadImg(['src','src']) or $('img').preloadImg()
* author: Cody Lindley
*/
(function($) {
// Internal cache of image src values.
var cache = {};
$.preloadImages = function( arr ) {
// For each passed image src value,
$.each( arr, function(i,src){
// If that value exists and isn't in the cache,
if ( src && !cache[ src ] ) {
// Preload the image.
var img = new Image();
img.src = src;
// Update the cache.
cache[ src ] = img;
}
});
};
$.fn.preloadImages = function() {
// If the length of the selected elements is non-zero, call $.preloadImages
// with an array containing all image src values.
this.length && $.preloadImages( $.map(this, function(elem){
return elem.src;
}) );
// Return the original jQuery collection.
return this;
};
})(jQuery);
@paulirish
Copy link

Like!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment