javascript - 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 毫秒并循环遍历所有图像标签,但这肯定不是要走的路,因为它很晦涩!
上面的结果是:
- 我在加载文件后立即收到
Now my images have fully loaded
消息,但在呈现所有内容后它不会等待显示消息 - 我根本没有收到
console.log(event)
消息 - 我根本没有收到任何
Load image event
消息
我正在通过使用 Chromes 网络选项减慢速度来调试它:
解决方案
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.
推荐阅读
- r - 根据拟合的坡度值更改 geom_smooth 的颜色
- python - 色调位置不一致的 Seaborn Barplot 标签
- dart - 为什么颤振错误中缺少源信息
- corda - Corda:试图将 RPC 权限放在外部数据库上
- java - 如何获取字符串并存储到数组中然后与列表进行比较
- python-3.x - 如何创建一个具有三重循环的加工条?
- bash - Solaris 中的日志轮换(压缩/删除)脚本
- azure - 作为 Azure Devops 构建管道的一部分预配 VM
- c# - 输出文件上的 System.IO.FileNotFoundException
- asp.net-mvc-5 - 在启用sustainsys OWIN 中间件时发出注销非SAML 身份验证用户的问题