在我的组件模板中,我有一个这样的容器
<div [innerHTML]="somehtml | safeHtml"></div>
HTML 包含带有标准图像标签的图像 喜欢
<img src="http://google.com/someimage.png"/>
我想知道我的 HTML 中的图像何时完全加载。我该如何检查?
P.S.: safehtml 只是一个 sanitizer 管道
编辑:我正在寻找基于事件的解决方案,而不是检查时间间隔!我还需要一个专门针对这个容器的解决方案
最佳答案
你可以尝试这样的事情。我不喜欢它,因为它不是 Angular 方式,但由于你的模板是一个字符串,我几乎不相信有更好的东西:
HTML:
<div [innerHTML]="somehtml | safeHtml" id="div-to-check"></div>
TS:
this.somehtml = `your html`;
window.setTimeout(() => { // Let's make it async to execute it in the next tick
const promises = Array.from(
document.querySelectorAll('#div-to-check img')
) // get all images
.map((img: HTMLImageElement) => {
if (img.complete) {
return Promise.resolve(); // Check if the image already loaded. Maybe it's been too fast
}
return new Promise((resolve, reject) => {
img.onload = resolve; // it resolves when it loads
img.onerror = reject; // avoids infinite waiting
});
});
Promise.all(promises)
.then(() => {
console.log('all images loaded!');
})
.catch(() => {
console.error('an image didn\'t load');
});
});
关于javascript - 如何检测 HTML 绑定(bind)中加载的所有图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56189774/