Preloading Content With jQuery

Creating dynamic websites that take advantage of AJAX, AHAH, and media with jQuery can lead to creations that aren't just functional but are fun with some eye candy. But, if your script is loading an image or other piece of media and it's jumpy rather than nicely fading in because your browser is loading the content your site quickly goes from cool to unprofessional. Thankfully, preloading content with jQuery is something that can be done fairly easily. Let's take a look at a couple ways to preload content.

Preloading Images

Update: This image preloading solution has been updated to a better solution that is explained in detail.

For some time there has been a snippet of code floating around the Internet that provides image preloading. To use it add the following function to your site (usually in a separate javascript file):
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

To take advantage of this plugin use it in a form like:

$.preloadImages("image1.gif", "/path/to/image2.png",
"some/image3.jpg");

Each argument to the function in this comma separated list should be a url to an image to load. It's that easy.

Preloading Content

Let's take this a step further. What if you received some content via AHAH and want to preload the media in that content before presenting it? This is a common use case for images. If this is your case here is a little trick that works. It's a modification of the code above.

First, the plugin code:

jQuery.preloadContent = function(){
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<div>").html(arguments[i]);
  }
}

Notice the change in the code here? Instead of placing an image path as an src element on an image tag we are taking the content and placing it as html on a div. This will preload the content and, just like with the image plugin, the content will not display at this point.

To use the code do something like:

$.preloadContent(myvar1, myvar2);

In these cases myvar1 and myvar2 are javascript variables that contain the html that needs to be preloaded.

After preloading your content will be cached in the browser and right at your fingertips to use.