Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delaying the loading of a certain css background image

in a CSS like this :

...
#big-menu {
    background: #fff url(../images/big-menu.jpg) no-repeat;
}
#some-menu {
    background: #fff url(../images/some-menu.jpg) no-repeat;
}
#some-other-menu {
    background: #fff url(../images/some-other-menu.jpg) no-repeat;
}
...

is there a way to delay the loading of #big-menu's background image, so that it loads after everything else, including all of the images in the HTML, and every other CSS background (the some-menu and some-other-menu).

The reason is, big-menu.jpg is very heavy in size, and I want it to be loaded last. After all, it just serves as an eye-candy, and there are other background images that have a better use than that. (such as the ones used in buttons)

Does the order of putting it in CSS or the occurrences of the markup (#big-menu) in HTML got anything to do with what gets loaded first ? or is there a more reliable way to control it ? javascript (jQuery preferred) is fine.

like image 566
andyk Avatar asked Feb 03 '09 05:02

andyk


3 Answers

The ordering in css doesn't control which resources are loaded first, but do affect what existing style is being overwritten or inherited.

Try the JavaScript onload event. The event executes only after the page is finish loading.

function loadBG(){
    document.getElementById("big-menu").style.backgroundImage="url(../images/big-menu.jpg)";
}
window.onload=loadBG();
like image 68
Jason Avatar answered Nov 08 '22 19:11

Jason


This might not be a perfect solution(as it is a css-background and not a image), but YUI Image loader provides a good way of lazy-loading images.

Create a group

var imgGroup = new YAHOO.util.ImageLoader.group(window, 'load', 2);

After the document has loaded, the image will load 2 seconds after it. See Yahoo! Shine or the examples for demo.

like image 4
Alagu Avatar answered Nov 08 '22 19:11

Alagu


Another solution is to split your assets over different domains, browsers will only request two assets at time then wait for one to be loaded before starting the next. You can observe this with Firebug and YSlow, so placing some assets on images.example.com and images1.example.com and see if that makes an impact

like image 4
Tom Avatar answered Nov 08 '22 19:11

Tom