Preload images with CSS, not JS

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.

Tirdad Chaharlengi, Senior Developer
#Drupal | Posted

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:

  1. <div id="preload">
  2. <img src="image1_on.jpg" alt="Image 1" />
  3. <img src="image2_on.jpg" alt="Image 2" />
  4. <img src="image3_on.jpg" alt="Image 3" />
  5. </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:

  1. <ul id="menu">
  2. <li class="menu-item-1">
  3. <a href="#"><img height="50" width="50" title="" alt="" src="image1_on.jpg"/>Menu link 1</a>
  4. </li>
  5. <li class="menu-item-2">
  6. <a href="#"><img height="50" width="50" title="" alt="" src="image2_on.jpg"/>Menu link 2</a>
  7. </li>
  8. <li class="menu-item-3">
  9. <a href="#"><img height="50" width="50" title="" alt="" src="image3_on.jpg"/>Menu link 3</a>
  10. </li>
  11. </ul>

Your CSS would then look something like this:

  1. #menu a {
  2. text-indent: -9000px;
  3. overflow: hidden;
  4. }
  5. #menu img {
  6. display: none;
  7. }

and then the appropriate image background properties for the links:

  1. #menu .menu-item-1 a {
  2. background: url(image1.jpg) no-repeat scroll 0 0;
  3. height: 50px;
  4. width: 50px;
  5. }
  6. #menu .menu-item-1 a:hover,
  7. #menu .menu-item-1 a:active {
  8. background: url(image1_on.jpg) no-repeat scroll 0 0;
  9. }
  10. 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.

Tirdad Chaharlengi

Senior Developer