Jquery 函数未在初始加载时触发

Jquery function not firing on initial load

我有一种情况,我必须等待 特定图像 加载,然后换出它的 src,或者找到下一张图像并 hide/show 它.

我需要做的是显示一个占位符图像(剪影)直到其主图像准备就绪,然后隐藏剪影并显示主图像。很普通的东西。

问题是这个 jquery 函数不会在新选项卡上触发,或者 window...但是如果我按 f5 它会完美运行...但是我又打开了一个新选项卡, 在我按下 f5 之前它不会触发。

CSS:
.staffImage1, .staffImage2, .staffImage3, .staffImage4, .staffImage5 { display: none; }

Jquery:
$('.staffImage1, .staffImage2,.staffImage3,.staffImage4, .staffImage5')
    .load(function () {
        $(this).next('.sillhouette').hide();
        $(this).show();
        console.log("function fired")
    })

我只在刷新后才收到日志消息。

需要注意的是我正在使用 "First 14k" 方法来提高页面速度,所以可能 jquery 只是在第一次最初加载图像时尚未准备好,但被缓存了并在 f5 之后工作?

每个图像必须等到它完全加载,它们在一个滑块中,所以我需要在它准备好后立即显示第一张幻灯片图像,我不能等到所有已准备好 5 张图片,因为这会减慢第一张幻灯片图片的速度。

感谢任何建议,谢谢

这个结构:

$('.staffImage1, .staffImage2,.staffImage3,.staffImage4, .staffImage5').load(...)

无法在所有图像加载完毕后通知您。 .load() 一次只能处理一张图片。而且,如果图像被缓存,它们可能在您的 jQuery 运行之前就已经完成加载,因此您会完全错过加载事件。

最简单的解决方法是在所有页面资源加载完成后使用 window 加载事件:

$(window).load(function() {
    // all images are loaded here
});

也可以只监视这 5 个图像,但这样工作量更大。我以前写过代码来执行此操作,所以我会看看是否可以找到之前的代码。


这里有一个 jQuery 插件功能,它只监视特定的图像。当 jQuery 对象中的所有图像都已加载时,它将调用其回调:

// call the callback when all images have been loaded
// if all images are already loaded or there were no images in the jQuery
// object, then the callback will be called immediately
jQuery.fn.imgsLoaded = function(fn) {
    var cntRemaining = 0;
    function checkDone() {
        if (cntRemaining === 0) {
            fn();
        }
    }

    function imgDone() {
        --cntRemaining;
        checkDone();
        // remove event handlers to kill closure when done
        $(this).off("load error abort", imgDone);
    }

    this.each(function() {
        if (!this.tagName.toLowerCase() === "img" && !this.complete && this.src) {
            ++cntRemaining;
            $(this).on("load error abort", imgDone);
        }
    });
    checkDone();
    return this;
}

你可以这样使用它:

$('.staffImage1, .staffImage2,.staffImage3,.staffImage4, .staffImage5').imgsLoaded(function () {
    $(this).next('.sillhouette').hide();
    $(this).show();
    console.log("function fired")
});

工作演示:http://jsfiddle.net/jfriend00/zaoweyoo/

编写jquery代码 '$(文档).ready(函数(){ //你的代码 });'