Reputation: 621
I have a hover element, when I mouseover it, the background image changes. This is fine, but it loads the image just when I mouseover it, not before, and I see blank box for a short while. How do I preload the images?
Upvotes: 0
Views: 144
Reputation: 5203
If it is a background-image
then you can use one of the following techniques:
Technique #1
Load the image on the element's regular state, only shift it away with background position. Then move the background position to display it on hover.
#grass { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background-position: bottom left; }
Technique #2
If the element in question already has a background-image applied and you need to change that image, the above won't work. Typically you would go for a sprite here (a combined background image) and just shift the background position. But if that isn't possible, try this. Apply the background image to another page element that is already in use, but doesn't have a background image.
#random-unsuspecting-element { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background: url(images/grass.png) no-repeat; }
Sources:
Duplicate Question answered by Fatih Hayrioğlu
Upvotes: 2
Reputation:
In the beginning of your body, load the image hidden:
<body>
<img src="myimage.png" style="display: none;" />
</body>
The browser will use it's cache to catch that same image to load as a background when you call it, thus without delay.
Upvotes: 2