jQuery Preloading External Images

This is how you might go about preloading images into the browser cache (Caching External Images) that will be later inserted into the page. This method would be useful only if you have many images and no control over the load order of the image containers. For example if you are grabbing the images for new tweets and then showing new tweets with user profile pictures. Before image loads from external server (Twitter in this example) there will be an ugly missing image icon.

Broken images…

images-not-cached

After a few seconds the images appear…

images-cahced

So lets preload the external images…

So when the tweets are loaded in (whichever method your using) you can add this snippet to cache the user profile image.

//cache the user img
$('img').hide().appendTo('body').one('load', function() {
   console.log('Image: '+$(this).attr('src')+' is cached...');
   $(this).remove();
});

Output in Firebug console
cahced-images-console-log

Output in Firebug net panel
images-cache-netpanel

That’s it your images should onw preload and not appear broken! :)