我有一个框架(vue.js),在页面更改时插入一些图像(使用路由器,而不是真正的页面刷新)。直接加载时,我可以让页面显示加载屏幕:
loading = true;
$(window).on( 'load', function(){
loading = false;
});
但是,如果页面已通过框架导航,则 $(window).on('load')
不会触发。 (我认为)这是因为 window
已经加载,并且新图像的加载不再与窗口绑定(bind)。因此,loading = false
永远不会触发,因为窗口已经加载。
这是一个极其简化的示例,但它说明了同一点:
//Loading the initial image, it works fine because it runs on window load.
console.log('Loading first image...')
$(window).on('load',function(){
console.log('First image loaded');
});
$('button').on('click',function(){
$('div').append('<img src="https://placekitten.com/200/300">');
console.log('Loading extra image...');
//This never triggers because the window is already loaded.
//I need something to trigger while the appended images are loading
$(window).on('load',function(){
console.log('Extra image loaded.');
});
});
HTML:
<img src="https://placekitten.com/200/300">
<button>Click to load extra</button>
<div></div>
这是一个codepen .
最佳答案
您可以使用唯一标识符向每个新图像添加 .load() 监听器,并使用数组跟踪它们,一旦加载所有图像,您就可以使用该数组来运行函数:
var loadingImages = [];
$('button').on('click',function(){
//Get unique identifier + add to 'loading'
var n = $('div').find("img").length;
loadingImages.push(n);
//Add image with unique classname
$('div').append('<img data-n="'+n+'" src="https://placekitten.com/200/300">');
//Attach load listener to new image
$('div').find("img[data-n="+n+"]").load(function(){
var n = $(this).attr('data-n');
//Remove from 'loading'
var index = loadingImages.indexOf(n);
loadingImages.splice(index, 1);
//if 'loading' empty, run function
if(loadingImages.length==0){
alert("Loaded All Images");
}
});
});
示例:JSFiddle
关于javascript - 窗口本身加载后如何触发加载事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912628/