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.
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.