I've always looked to Facebook when it comes to adding new features to my own website. I mean, why not? Certainly 500(estimate/exaggeration) developers must be smarter than 1. I also look at it like a learning experience trying to emulate all their awesome features.

I've already emulated their photo tagging functionality so while I was working on that project, I thought, why not steal their image preloading idea as well.

You may have noticed that when browsing photo albums on Facebook, images seem to load super fast when clicking the next/previous buttons or hitting left/right on your keyboard. There's a reason for this. Facebook is preloading the previous and next image.

Firebug's Net Panel

Firebug's Net Panel

Using Firebug's net panel you can see how each time I hit next, Facebook loads one image ahead and one image back. That means I always have the next and previous images loaded ahead of time.

On To The Code...

The code in it's simplest form is easy, especially with jQuery.

var nextimage = "/images/some-image.jpg"; $(document).ready(function(){ window.setTimeout(function(){ var img = $("<img>").attr("src", nextimage).load(function(){ //all done }); }, 100); });

setTimeout Explanation

The reason I wrap this in setTimeout is to take it out of the linear flow of JavaScript as Steve Sounders explains -

use setTimeout to kick off long executing code - If you have a function that takes a long time to execute, launching it via setTimeout allows the page to render and resources to download without being blocked.

Further Reading