Friday, July 16, 2010

How to quickly cache images for css using jQuery

Please note, there are other ways of doing this, but this is a quick method for caching images for your page, using a very simple piece of jQuery.

If you use CSS to change the backgrounds on an element when a user moves their mouse over it you will the new image to display as soon as it happens. If the browser has no record of the image then it has to has immediately send a request to the server for the image. This can take precious seconds and in some cases, could spoil the whole look of your well designed element.

There are a number of fancy jQuery functions that may allow you to do this in a more compliant standard, but I can't see any harm doing it this way:

1. Create an empty element within your webpage (I put it just before </body>), for the case of the example, our element is a div element named 'imageCache':

<div id="imageCache"></div>

2. Set its display attribute to none, like so:

#imageCache{display:none;}

This stops the element from showing when the browser displays the page.

3. In your jQuery code, set the HTML of the element to use the images, in your document.ready function like so:

$(document).ready(function() {
$('#imageCache').html('<img src="image1" /> <img src="image2" />');
})


4. The Images will not appear as they are inside an element which has no visibility thanks to the CSS.

Hey Presto, your images are now ready to be used.

Some people may say that the element should not be added to the web-page unless it is to be used to display something. They may have a point, but if you want a quick solution and you are a jQuery newbie, this will do you just fine and will still pass W3C validation. If that is the case and you do not want an empty tag floating around your HTML source code then use jQuery's 'append' function and add the element in to the DOM and add the images using that method, like so:

$('body').append('<div id="imageCache"><img src="image1" /> <img src="image2" /></div>');

Please also note that this could be done entirely using CSS whereby you load in the images directly in to the HTML within your element, they would still be hidden because of the CSS, the above method is the alternative using jQuery.

Labels: , , ,