16

I have a link that starts with one background image and then changes on hover to another. Both background images are set in the CSS. My browsers (any of them) don't seem to load the hover image until you actually hover. But then you end up with a blank image for the several seconds (on my very slow connection) it takes to load the new one. Is there a way to encourage the browser to pre-load the hover image so that delay time doesn't occur on hover?

19

1) Use CSS Sprites (This is the preferred method).

2) Load the images in a hidden div. Place the images in the div and then set the div's CSS to display: none; to hide it.

3) Load the images with CSS:

#preloadedImages
{
    width: 0px;
    height: 0px;
    display: inline;
    background-image: url(path/to/image1.png);
    background-image: url(path/to/image2.png);
    background-image: url(path/to/image3.png);
    background-image: url(path/to/image4.png);
    background-image: url();

}

4) Use this JavaScript

<script language="JavaScript">

function preloader() 
{
     // counter
     var i = 0;

     // create object
     imageObj = new Image();

     // set image list
     images = new Array();
     images[0]="image1.jpg"
     images[1]="image2.jpg"
     images[2]="image3.jpg"
     images[3]="image4.jpg"

     // start preloading
     for(i=0; i<=3; i++) 
     {
          imageObj.src=images[i];
     }
}
</script>
| improve this answer | |
10

I don't really like the javascript solution - it's messy, difficult to maintain, and of course completely fails when JS is disabled.

The modern solution is to use CSS Sprites - try it, believe me, you'll wonder why you never did this before ;)

| improve this answer | |
1

I found this link on how to pre-load images using pure CSS:

http://www.thecssninja.com/css/even-better-image-preloading-with-css2

And it worked for me when I need to change the different background images on hover.

| improve this answer | |
  • It works nicely with Safari and Chrome, but still does not work in 2020 for Firefox. – Chewie The Chorkie Mar 12 at 20:11
0

Add this above your CSS:

<script type="text/javascript">
var images = ['img1.jpg', 'img2.jpg'];

for(var i = 0, len = images.length; i < len; i++) {
  new Image().src = images[i];
}
</script>
<link rel="stylesheet" type="text/css" href="your_css_file.css" />

If you go the sprite route as danp suggests you still have an issue with loading the sprite before it's needed. That said I love sprites; to easily make them I use the spriteme tool from Steve Souders:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.