timkl
timkl

Reputation: 3339

Delay when loading CSS background images

I have some tabs for my website where the background-image changes when you click on them.

However when I hover over the tabs the first time after the DOM has loaded, there's a slight delay before the hover-image show, resulting in a jarring effect.

I don't know how to troubleshoot this, any ideas? :)

Live example here: http://jsfiddle.net/timkl/fjupq/ - the delay is not as long on JSFiddle's server - but it's still there.

Upvotes: 6

Views: 7337

Answers (3)

MeSo2
MeSo2

Reputation: 466

Another way to do this is to have that image somewhere else displayed, preferably at the end of the page, as a 1px to 1px image, and have it placed outside the page layout. This will preload the image.

Upvotes: 0

Ross
Ross

Reputation: 14415

A simple solution is to use javascript to pre-load the image. Include this in the HEAD of the page:

<script type="text/javascript">
    var img = new Image(); 
    img.src = "http://dummyimage.com/200x10/000000/fff"; // background image
</script>

Upvotes: 3

No Results Found
No Results Found

Reputation: 102755

The solution to this is to use sprites instead of separate images.

You use a single image, and instead of changing the background source on :hover, you simply change the background position. This way, the entire image is loaded in advance.

For example, check out Stack Overflow's sprite sheet:

You don't have to take it to this extreme, you can just have one image that has both the normal and :hover states, and move it to the left/right or up/down.

Upvotes: 11

Related Questions