0

There is a div #container which contains various divs with large background images,

I want to use some Pre-Image loading js for avoiding the ugly look of loading image.

But the problem is that I can't find any script which loads all images in background and instead in #container display a loading bar.

Though Internet is full of scripts which loads images for whole body but I want just for an element meanwhile everything else is visible such as content.

UPDATED Question: Would the following script work for the background images specified in CSS?

$('#container img:last').load(function(){ 
  //do stuff
});

UPDATE:Best solution is get hold of this jQuery plugin, its called "preloadCssImages". You can find it here.

It pre loads all the css images present without even bothering to do this all stuff.

Suraj
  • 932
  • 5
  • 23
  • 43

3 Answers3

1

You can wait for the last image in the container to load then perform your actions. so something like this

$('#container img:last').load(function(){ //do stuff });

jarvo
  • 36
  • 3
  • 1
    You could load the image and then set it as the background image or something like this $('').attr('src', 'http://picture.de/image.png').load(function() { $('body').css('background-image', 'url(http://picture.de/image.png)'); }); found it here http://stackoverflow.com/questions/5057990/jquery-background-image-loaded-check – jarvo Apr 10 '11 at 05:06
  • Rather than setting all the backgrounds inline, you should just apply a "loaded" class to `` and in your CSS have the background images applied under `body.loaded #example { background:...` for example. – Marcel Apr 10 '11 at 05:25
1

First set a loading image within the container:

<div id="container"><img src="loading.gif" class="loading"/></div>

When all images load complete, then empty #container div and append all images into the div like this:

$('#container img:last').load(function(){
$('#container img.loading').remove();
})
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1

An elegant solution is to use CSS cascading. HTML:

<body>
    <div class="c1"></div>
    <div class="c2"></div>
</body>

CSS:

.c1 { background: #fff }
.c2 { background: #eee }
.loadimages .c1 { background: url(big1.jpg); }
.loadimages .c2 { background: url(big2.jpg); }

JS (on load or whenever you're ready):

document.getElementsByTagName('body')[0].className += 'loadimages';

Most browsers only load unused images as needed, or load it after the window load event is fired. However, images are also put in the load queue in the order that they are encountered, so even if the JS above is executed on DOM ready, it will still load the images after all the other images that are not cascaded behind the .loadimage class.

Sajid
  • 4,381
  • 20
  • 14