Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tirams
Created February 15, 2012 07:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tirams/1833910 to your computer and use it in GitHub Desktop.
Save tirams/1833910 to your computer and use it in GitHub Desktop.
jQuery plugin to preload images
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function (callback)
{
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
var checklist = this.toArray();
var removeImg = function (element)
{
for (var i = 0; i < checklist.length; i++)
{
if (checklist[i] == element) { checklist.splice(i, 1); }
}
};
this.each(function ()
{
$('<img>').attr({ src: this }).load(function ()
{
removeImg($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment