Javascript - 在加载所有图像后执行 [英] Javascript - execute after all images have loaded
本文介绍了Javascript - 在加载所有图像后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
读过其他人的问题我认为
Having read other people's questions I thought
window.onload=...
会回答我的问题。我已经尝试了这个,但它在页面加载的瞬间执行代码(不是在图像加载后)。
would answer my question. I have tried this but it executes the code the instant the page loads (not after the images load).
如果它有任何区别,图像来自CDN和不是相对的。
If it makes any difference the images are coming from a CDN and are not relative.
任何人都知道解决方案吗? (我没有使用jQuery)
Anyone know a solution? (I'm not using jQuery)
推荐答案
这是现代浏览器的快速入侵:
Here is a quick hack for modern browsers:
var imgs = document.images,
len = imgs.length,
counter = 0;
[].forEach.call( imgs, function( img ) {
img.addEventListener( 'load', incrementCounter, false );
} );
function incrementCounter() {
counter++;
if ( counter === len ) {
console.log( 'All images loaded!' );
}
}
加载所有图像后,您的控制台将显示所有图片都已加载!。
Once all the images are loaded, your console will show "All images loaded!".
此代码的作用:
- 加载文档中变量中的所有图像
- 循环显示这些图像
- 为每个图像上的load事件添加一个监听器运行
incrementCounter
函数 -
incrementCounter
将递增计数器 - 如果计数器已达到图像长度,则意味着它们已全部加载
- Load all the images in a variable from the document
- Loop through these images
- Add a listener for the "load" event on each of these images to run the
incrementCounter
function - The
incrementCounter
will increment the counter - If the counter has reached the length of images, that means they're all loaded
有此跨浏览器方式的代码不会那么很难,它就像这样更干净。
Having this code in a cross-browser way wouldn't be so hard, it's just cleaner like this.
这篇关于Javascript - 在加载所有图像后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文