Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay when loading CSS background images

Tags:

html

css

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.

like image 578
timkl Avatar asked Jan 16 '12 12:01

timkl


2 Answers

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

  • http://css-tricks.com/css-sprites/

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:

  • http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4

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.

like image 107
Wesley Murch Avatar answered Sep 30 '22 15:09

Wesley Murch


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>
like image 40
Ross Avatar answered Sep 30 '22 14:09

Ross