Skip to content

Instantly share code, notes, and snippets.

@metaphox
Created February 10, 2012 00:21
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 metaphox/1784744 to your computer and use it in GitHub Desktop.
Save metaphox/1784744 to your computer and use it in GitHub Desktop.
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
//Out of interest, in my context, I'm using this as follows:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment