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";
Wordpress Super Ninja » 3 Ways to Preload Images with CSS, JavaScript, or Ajax
3 Ways to Preload Images with CSS, JavaScript, or Ajax | Webplus - web developer resource blog
I thought of a solution to the incompatibility of IE8 & IE7 with multiple background-image (doesn’t work in IE6).
This does involve extra markup so I realize that maybe this would make people cringe at that thought but it depends on how important IE8 support is to you. (sadly many people are still using XP)
The process is essentially the same except instead of using multiple background-images we use a multiple class method.
#preload.img1 {background:url() no-repeat -9999px -9999px;}
#preload.img2 {background:url() no-repeat -9999px -9999px;}
#preload.img3 {background:url() no-repeat -9999px -9999px;}
#preload.img4 {background:url() no-repeat -9999px -9999px;}
#preload.img5 {background:url() no-repeat -9999px -9999px;}
#preload {display:none;} (optional of course)
This will insure that every browser is supported even IE7 & IE8…I couldn’t bring myself to give a crap about IE6 so not going to bother with figuring out a solution for that.
Thanks for sharing that Michael. I agree the compromises sometimes have to be made in order to support IE. I don’t bother supporting IE6 anymore either, though.