如何在页面中所有图片加载完成后运行jQuery代码?
$(window).load(function(){})
检查所有图片是否已加载有些麻烦,因此除非你有迫切需要如此精确,否则检查所有图像和其他内容是否已加载要简单得多:
$(window).load(function() { ... });
这个代码使用了jQuery的.load() 方法。
如果你确实需要检查图片,那么情况会变得更加棘手。我最初想要做的是:
$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!
然而,以上代码创建了一个包含所有图片的 jQuery 对象,然后将 function() { ... }
绑定到每个这些图片上。因此,以上代码将根据页面上存在的图像数量触发函数相应次数!
为了解决这个问题,我们应该检查页面上有多少张图片,并在所有这些图片加载完成之后仅触发一次函数:
$(function() {
// To keep track of how many images have loaded
var loaded = 0;
// Let's retrieve how many images there are
var numImages = $("img").length;
// Let's bind a function to the loading of EACH image
$("img").load(function() {
// One more image has loaded
++loaded;
// Only if ALL the images have loaded
if (loaded === numImages) {
// This will be executed ONCE after all images are loaded.
function() { ... }
}
});
});
$(function() {
var length = $('img').length ;
var counter = 0;
$('img').each(function() {
$(this).load(function(){
counter++;
if(counter == length) {
Callback(); //do stuff
}
});
});
});
$("img").load()
来代替 $("img").each(function() { $(this).load() })
来删除一行代码 - 请看我的编辑后的答案。 - Peter Ajtai$('img').on('load', function(){
$('img').off('load'); //detaches from load event, so code below only executes once
// my code to execute
});
这不是直接的答案,但是仍然值得参考。
请参考以下内容
代码
$(window).bind("load", function() {
// code here
});
@Peter Ajtai的回答除了在IE缓存图像上无法工作。为了让它在IE上正常工作,以下是一个解决方案: https://dev59.com/pm865IYBdhLWcg3wUs3z#3877079或者使用imagesLoaded插件。
对于使用jQuery的任何人来说,这个小片段就可以解决问题(它确保在运行其中任何脚本之前加载所有图像)...
$(window).bind("load", function() {
// code goes here here
});
load
事件也会被触发吗?我不太确定。 - Peter Ajtai