Preload images with CSS, not JS

Posted Jun 18, 2009 // 0 comments
Tirdad:

A common solution to avoid flickering when using rollover images is to rely on some Javascript / JQuery snippet to preload those additional “on” state images. While this is fine in most cases, this method has the disadvantages of adding extra JS processing and it will not work on IE7 for background images referenced in your CSS files.
The better alternative is to use the strictly CSS solution of having your images appear in your HTML but with their display property set to none:

<div id="preload">
<img src="image1_on.jpg" alt="Image 1" />
<img src="image2_on.jpg" alt="Image 2" />
<img src="image3_on.jpg" alt="Image 3" />
</div>

and then setting this up in your CSS:
div#preload {display:none;}

Even better, avoid gunking up your HTML with extra mark-up by directly referencing these images in your HTML. Here’s an example for a menu with rollover image links:
<ul id="menu">
<li class="menu-item-1">
<a href="#"><img height="50" width="50" title="" alt="" src="image1_on.jpg"/>Menu link 1</a>
</li>
<li class="menu-item-2">
<a href="#"><img height="50" width="50" title="" alt="" src="image2_on.jpg"/>Menu link 2</a>
</li>
<li class="menu-item-3">
<a href="#"><img height="50" width="50" title="" alt="" src="image3_on.jpg"/>Menu link 3</a>
</li>
</ul>

Your CSS would then look something like this:
#menu a {
text-indent: -9000px;
overflow: hidden;
}
#menu img {
display: none;
}

and then the appropriate image background properties for the links:
#menu .menu-item-1 a {
background: url(image1.jpg) no-repeat scroll 0 0;
height: 50px;
width: 50px;
}
#menu .menu-item-1 a:hover,
#menu .menu-item-1 a:active {
background: url(image1_on.jpg) no-repeat scroll 0 0;
}
and so on

P.S.: of course if you have the option of using CSS sprites to merge all these elements into one single image, you’ll avoid the whole need for preloading in the first place. That is an even better method than the one shown here, since you’ll also lower the number of http requests made for your images, but ideally it’s one that should have been already considered at the cut-up phase.

About Tirdad

Tirdad Chaharlengi is a software developer with experience in an eclectic selection of environments, ranging from a computer game company, Nevrax to the Internet division of TF1, France's leading private television channel.

Tirdad ...

more >

Read Tirdad's Blog

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <strong> <code> <p> <img> <ul> <ol> <li> <h2> <h3> <h4> <b> <u> <i>
  • You may insert videos with [video:URL]

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.