在继续之前,验证所有图像是否都在`$(window).load()`函数中加载

时间:2010-09-08 14:53:44

标签: jquery slideshow document-ready

我正在为一个页面添加一些用于幻灯片放映的大图像,但我想在页面的正常部分完全加载(包括图像)时开始加载这些图像。

为此,我在$(window).load()函数中添加图像:

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 );

});

幻灯片放映slideSwitch()应该在所有图片完全加载时开始,但就像现在一样,它会在元素添加到DOM时开始。

我无法将循环移动到document.ready函数,因为我不希望幻灯片放映干扰正常图像的加载。

如何在设置间隔之前检查是否已加载所有图像?

1 个答案:

答案 0 :(得分:4)

试试这个:

// 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');
});
相关问题