12 Aug 2009

Preloading images without Javascript, using CSS instead

If I can find a way of using CSS for something I would normally do with Javascript, I will always go with CSS. It also usually works out easier and cleaner in CSS.

When displaying my 2 stage CSS buttons on a page I was working on, the second stage took a few moments too long to load, so I decided I wanted to preload those images using CSS.

Here is my solution...

The CSS:

img.preload { display: none; width: 1px; height: 1px; }

The HTML:

<img src="./path/to/image.jpg" alt="preloaded" class="preload" />

Just add the class preload to each image and you should be laughing.