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

标签 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 函数,因为我不希望幻灯片放映干扰正常图像的加载。

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

最佳答案

试试这个:

// 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');
});

关于jquery - 在继续之前验证所有图像是否已加载到 `$(window).load()` 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669017/

相关文章:

document.ready 上的 jQuery animate()

javascript - document.ready 与 document.onLoad

php - Yii - ajax 加载表单元素的用户端验证

php - 将 jquery attr 连接到 PHP Mysql?

javascript - SlideS 的选项生成 NextPrev 不起作用

javascript - jQuery $(document).ready () 触发两次

javascript - 如何选择div下的第二个表结构?

javascript - jQuery - 从按钮组获取事件按钮(输入类型 = "radio")

css - 使用下一个和上一个按钮实现仅CSS的幻灯片/轮播吗?

html - 周期 2 上一个和下一个