Preloading Images

UPDATE: Now that all modern browsers (that is, everything except IE8 and older) have support for multiple background images via CSS3, that is my preferred method. It’s detailed by Jeff Starr in his post, Better Image Preloading with CSS3.

* * * *

I’ve been looking for a good way to preload images for rollovers, but it seems like a lot of the common methods have problems.

  • There are reliability issues using a JavaScript Image object or document.write()
  • Some browsers won’t load a display:none containing element

So far the best way I’ve found is Perishable Press’ Better Image Preloading without JavaScript method. You can set the hover images as the background on the regular image, and then position it outside of the image, so it doesn’t show up:

#foo1 {background: url(foo1-hover.png) no-repeat -500px -500px ;}
#foo2 {background: url(foo2-hover.png) no-repeat -500px -500px ;}
#foo3 {background: url(foo3-hover.png) no-repeat -500px -500px ;}

The problem I have with this one, though, is that the hover images will be loaded with the rest of the page, making it slower. I don’t think they should be loaded until after the rest of the page has finished loading. So, I used SitePoint’s addLoadEvent() to assign the background images after the page loads:

document.getElementById("foo1").style.background = "url(foo1-hover.png) no-repeat -500px -500px";
document.getElementById("foo2").style.background = "url(foo2-hover.png) no-repeat -500px -500px";
document.getElementById("foo3").style.background = "url(foo3-hover.png) no-repeat -500px -500px";

Trackbacks for this post

  1. Wordpress Super Ninja » 3 Ways to Preload Images with CSS, JavaScript, or Ajax
  2. 3 Ways to Preload Images with CSS, JavaScript, or Ajax | Webplus - web developer resource blog

Leave a Comment

 
re-abolish slavery