вторник, 27 май 2008 г.

Preloading Content With jQuery

Preloading Images



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.

Няма коментари: