By Sam Deering

jQuery Preloading External Images

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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…



After a few seconds the images appear…


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...');

Output in Firebug console

Output in Firebug net panel

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

Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?