首页 > 解决方案 > jQuery load() 以及如何知道动态添加的图像何时完成加载?

问题描述

使用 jQuery 3.3.1 load(),我在img里面添加了一些 HTML 标签的内容,然后我想在所有图片完成加载后检查视口中的可见元素。

我的问题是我无法知道动态添加的图片何时已完全加载到我的<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 毫秒并循环遍历所有图像标签,但这肯定不是要走的路,因为它很晦涩!

上面的结果是:

我正在通过使用 Chromes 网络选项减慢速度来调试它:

使用 Google Chrome 加速调试

标签: javascriptjqueryajax

解决方案


The reason your Load image event??? log is not firing, because you are not late binding the event handler on the images, thus, the on function will not fire for images that were added dynamically to your html.

To late bind, you can modify that function the following way:

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

But if an image takes a long time to load, and you are trying to do something after all the new images were loaded which came from your image-list.html, I suggest something like the below approach:

Try putting the load listener, inside the callback function of the load method, like this:

$("#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");
   }); 
});

You just have to be careful, as apparently, the load event will not fire, if the image you are loading was already cached, and loaded from the cache. There are workarounds for that too.

EDIT: The above code will take care for the situation where the images are loaded from cache also.


推荐阅读