jQuery load()以及如何知道动态添加的图像何时完成加载?

时间:2019-01-20 12:26:42

标签: javascript jquery ajax

使用jQuery 3.3.1 load()时,我要在其中添加一些HTML img标签的内容,然后要在视口中检查可见元素 所有图片都已加载完毕。

我的问题是我不知道何时将动态添加的图片完全加载到<div id="#content">中。

这是我用于加载新内容的JS代码:

// Replace the #content with content from a file containing a few `img` tags
$("#content").load("image-list.html", function() {
    console.log("Now my images have fully loaded???");
});

我已经尝试过了:

// Show me which event is triggered after load()
$(window).on("load resize scroll", function(event) {
    console.log(event);
});

// Check if I can get when the images have fully loaded
$("img").on("load", function() {
    console.log("Load image event???");
});

我还尝试了一些黑魔法,等待X毫秒并遍历所有图像标签,但这肯定是行不通的,因为它晦涩难懂!

以上结果为:

  • 加载文件后,我立即收到Now my images have fully loaded消息,但是在所有内容渲染完毕后,它都不会等待显示该消息。
  • 我根本没有收到console.log(event)消息
  • 我什么都没收到Load image event消息

我通过使用Chromes网络选项降低速度来调试此问题:

Speed debugging with Google Chrome

1 个答案:

答案 0 :(得分:1)

Load image event???日志未触发的原因,因为您没有在图像上绑定事件处理程序,因此,on函数将不会触发动态添加到html的图像

要进行后期绑定,您可以通过以下方式修改该功能:

$(document).on('load', 'img', function() {
    console.log("Load image event???");
});

但是,如果图像加载时间很长,并且您在尝试加载image-list.html中的所有新图像后都尝试执行某些操作,则建议采取以下方法:

尝试将负载侦听器放在load方法的回调函数中,如下所示:

$("#content").load("image-list.html", function() {
   var numberOfImages = jQuery("#content img").length;

   $("#content img").one('load', function() {
      numberOfImages--;
      if (numberOfImages == 0) {
           console.log("All the images have loaded");
      }
   });

   $("#content img").each(function() {
       if (jQuery(this)[0].complete) jQuery(this).trigger("load");
   }); 
});

您只需要注意,很明显,如果正在加载的图像已经被高速缓存并从高速缓存加载,则load事件不会触发。也有解决方法。

编辑:以上代码将注意从缓存中加载图像的情况。