JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some sleep(5) in my server side script. I implemented the following solution based off yours which seems to solve this.
Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.
// 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 }); });
Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.
$.each(arguments,function(){(new Image).src=this});