Pet*_*tai 20
检查是否已经加载了所有图像,因此除非您需要如此精确,否则检查所有图像和其他所有图像都已加载更容易:
$(window).load(function() { ... });
Run Code Online (Sandbox Code Playgroud)
这使用了jQuery .load()方法.
如果你确实需要特别检查图像,那么事情会变得有点棘手.我最初想要这样做:
$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!
Run Code Online (Sandbox Code Playgroud)
但是,上面创建了一个包含所有图像的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() { ... }
}
});
});
Run Code Online (Sandbox Code Playgroud)
小智 5
$(function() {
var length = $('img').length ;
var counter = 0;
$('img').each(function() {
$(this).load(function(){
counter++;
if(counter == length) {
Callback(); //do stuff
}
});
});
});
Run Code Online (Sandbox Code Playgroud)