Even better image preloading with CSS2

Recently I read an article on better image preloading using CSS3 which presented a clever idea using CSS3 multiple background images to preload images on one element as opposed to another method of having containers for each image. As of writing the support for multiple backgrounds is fairly sparse with webkit having the best support (Safari 3+ & Chrome 1+), Firefox is introducing this in the upcoming 3.6 release.

There’s a better way

The article instantly got me thinking on a potential alternate method to accomplish the same task, but using a widely available CSS2.1 property. Which if possible will up the browser support significantly. Thankfully the idea actually worked.

CSS generated content

In CSS2 a content property was introduced, which in conjunction with the :before and :after pseudo-elements allows us to generate content in a document. The most interesting value that can be used with the content property is url() which allows us to pass an image.

content: url(img01.jpg);

That’s all great than we can add a single preloaded image using the content property but what about multiple images? That’s where the content property shows its true power, we can pass multiple url’s.

content: url(img01.jpg) url(img02.jpg) url(img02.jpg)

Brilliant, we can now preload multiple images using one line of CSS. We have all the benefits of the CSS3 method without the CSS3 and the Browser support grows exponentially.

  • IE8+
  • FF2+
  • Safari 3+
  • Chrome 1+
  • Opera 9.62+

Putting it all together

Now we know how to preload multiple images using CSS2, lets put it all together:

content: url(img01.jpg) url(img02.jpg) url(img03.jpg);
display: none;

Instead of creating an empty div with a class on it, we can utilise the requirement of the :after (or :before) pseudo-element. This needs to be there for the content property to work. We apply it to generate the content after the body tag and then set it to display: none, that way the preloaded images aren’t shown but are still loaded. We know have a pure CSS solution that requires no mark-up.

Almost perfect

IE6 and 7 do not support CSS generated content and therefore will not preload any images, but that’s a minor trade off. Users of IE6/7 will just have to load the images when they are called rather than getting them from the cache.

A possible work around for their lack of support is to use conditional comments to load the images. This solution will require extra mark-up.