Pre-load images with CSS

January 8, 2009 by Nicki  

Most anyone who’s been messing around with webpages and HTML over the past few years I’m sure is familiar with the concept of pre-loading images. If you have a rollover effect (for instance, mouseover effects on a menu bar), it makes good sense to pre-load your images so that the effect shows up immediately when your visitor moves their cursor over the image/object. For a long time, the most popular way to accomplish this was by adding javascript to your HEAD section and an onload snippet to your BODY tag.

There is a much easier way to do this with CSS. I had ran across this a long time ago, but never bookmarked the link.

Bad designer, BAD! whipping bad smiley

Luckily, I ran across it again recently and thought I’d post it here in case anyone else was interested in how to do this.

In your stylesheet, add the following:

.hiddenpic {display:none;}

Then add your image that you want pre-loaded just following the </HEAD> tag. For example:

<img src="/images/navhover.gif" alt="" class="hiddenPic" />

OR, you could put several images inside a DIV:

<div class="hiddenPic"><img src="/images/hover1.gif" alt="" /> <img src="/images/hover2.gif" alt="" /> <img src="/images/hover3.gif" alt="" /></div>

Just keep in mind that these images will load before you page does, so don’t overdo it with HUGE images!

Comments

3 Responses to “Pre-load images with CSS”

  1. Flash Buddy (1 comments.) on January 8th 2009 at 1:41 pm

    Nice tip there. I’ll give ‘er a go next chance. Thanks.

    Flash Buddy´s last blog post: Free Twitter Background Template

  2. Jeremy Flint (1 comments.) on January 9th 2009 at 11:09 am

    The way I do nav rollovers (when I actually need to use images) is with background images in css, and put the on and off states in the same image, then just change the background-position on the a:hover class.

    Jeremy Flint´s last blog post: How To Talk Dog

  3. Mr. Catalan on January 17th 2009 at 12:44 pm

    Fantastic solution!



Note: all comments automatically close 120 days past the post date.