检测何时加载了添加到DOM的图像 [英] Detect when images added to DOM have been loaded
本文介绍了检测何时加载了添加到DOM的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比如说,用户打开一个页面,点击一个按钮,然后出现带有图像的弹出窗口。如何检测所有图像何时加载?我不能在这里使用 window.onload
,因为该页面已经加载了所有资产。为了说清楚,我想找出弹出窗口的最终范围。
Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload
here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.
Popup被添加到DOM中,如下所示:
Popup is added to DOM like so:
var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);
推荐答案
基于这个答案。希望这就够了。
var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
d('loaded');
})
function d(s) {
var text = document.createTextNode(s);
cons.appendChild(text);
var br = document.createElement('br');
cons.appendChild(br);
}
function waitForImages(el) {
var images = document.querySelectorAll('img');
return Promise.all(_.compact(_.map(images, function(img) {
if (img.complete) {
d('img.complete');
return;
} else
return new Promise(function(resolve, reject) {
img.addEventListener('load', function() {
d('onload event');
resolve();
});
});
})));
}
.popup {
overflow: hidden;
}
img {
float: left;
margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>
这篇关于检测何时加载了添加到DOM的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文