views:

46

answers:

1

I am adding a number of large images for a slide-show to a page, but I want to start loading these images only when the normal part of the page is completely loaded (including the images).

To do that, I am adding the images in the $(window).load() function:

var slide_total = 20;

$(window).load(function() {

    for (i = 2; i <= slide_total; i++)
    {
        content = '<li><img src="/images/header' + ((i < 10) ? '0' : '') + i + '.jpg" width="960" height="314"></li>';
        $("#slideshow li:last-child").after(content);
    }

    slide_interval = setInterval( "slideSwitch()", slide_duration );

});

The slide-show slideSwitch() should start when all images are loaded completely, but as it is now, it starts the moment the elements are added to the DOM.

I cannot move the loop to the document.ready function as I don´t want the slide-show to interfere with the loading of the normal images.

How can I check whether all images are loaded before setting the interval?

+2  A: 

Try this:

// get the total number of images inserted in the DOM
var imgCount = $('#slideshow img').length;

// initialize a counter which increments whenever an image finishes loading
var loadCounter = 0;

// bind to the images' load event
$("#slideshow li img").load(function() {

    // increment the load counter
    loadCounter++;

    // once the load counter equals the total number of images
    // set off the fancy stuff
    if(loadCounter == imgCount) {
        slide_interval = setInterval( "slideSwitch()", slide_duration );
    }
}).each(function() {

    // trigger the load event in case the image has been cached by the browser
    if(this.complete) $(this).trigger('load');
});
karim79
Just to add, I am successfully using the above technique in one of our web apps, which requires that something fires once all images in part of the document have fully loaded.
karim79
Thanks, but it does not seem to work. In IE8 and IE7 the slide-show starts while the images are still loading. Are you sure the jquery `load()` method can be used like that?
jeroen
@jeroen - yes, I'm pretty sure :) Are you counting the correct images? I mean, try alerting the image count to ensure it is correct.
karim79
Sorry, my mistake, it´s working perfectly!
jeroen