3

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

为此,我在$(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函数,因为我不希望幻灯片干扰正常图像的加载。

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

4

1 回答 1

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');
});
于 2010-09-08T14:58:19.537 回答