如果图像已经加载,则jQuery.load()回退

jQuery .load() fallback if image is already loaded

本文关键字:load jQuery 回退 图像 加载 如果      更新时间:2023-09-26

Im使用jQuery load()函数绑定到图像的onload事件,以轻轻地将它们转换进来。

问题是,如果在调用image.load()函数之前已经加载了映像,则回调函数永远不会触发。

在我调用load()之前,有没有一种方法可以检测图像是否已经加载?

原因是它是一个提线木偶应用程序,在视图之间移动图像会被缓存,并且可能在调用渲染函数之前就已经加载了。

基本上我的代码在哪里:

preloadImages: function () {
        var images = $('.grid .item > img');
        var initialHeight = images.eq(0).width();
        images.each(function(){
            $(this).height(initialHeight).css("opacity", 0);
            $(this).load(function(){
                $(this).css("height", "").animate({"opacity": 1}, 200);
            })
        });
    }

在我调用load()之前,有没有一种方法可以检测图像是否已经加载?

是的。img元素具有complete标志,因此:

images.each(function() {
    var $this = $(this);
    $this.on("load", handleLoad);
    if (this.complete) { // `this` = the DOM element
        $this.off("load", handleLoad);
        handleLoad.call(this);
    }
});

(请注意,这是简化的,我省略了测量第一个img的代码—除非CSS强制使用特定宽度—并且使用handleLoad而不是内联函数,否则您需要等待加载,直到加载。)

注意事物的顺序:

  1. 首先,挂接load事件。

  2. 然后检查complete

  3. 如果complete为true,则取消挂起load并直接调用处理程序。

为什么要这样做?因为即使主JavaScript UI线程只有一个线程,浏览器也不是单线程的。因此,如果您执行了if (!this.complete) { $(this).on("load", handleLoad); },那么代码看到complete没有设置是完全有效的,然后在您可以将加载事件挂接到下一行之前,浏览器会触发load事件;由于浏览器当时检查了已注册事件处理程序的列表,但没有找到任何事件处理程序,因此不会对任何事件回调进行排队。这不太可能,但有效。

另一种方法是使用jQuery的one函数,该函数注册一个在第一次调用时注销自身的处理程序:

images.each(function() {
    var $this = $(this);
    $this.one("load.myload", handleLoad);
    if (this.complete) { // `this` = the DOM element
        $this.trigger("load.myload");
    }
});

注意名称空间(.myload)。您不希望激发其他可能已经激发或排队的load处理程序。