我正在尝试从chrome扩展端获取页面上的所有图像,然后在这些图像上执行一些代码,有时网站会延迟加载图像(例如,当用户向下滚动时)
有什么方法可以确保全部加载?我尝试向下滚动到窗口的底部,但无法使用分页。
export function imagesHaveLoaded() {
return Array.from(document.querySelectorAll("img")).every(img => img.complete && img.naturalWidth);
}
return Promise.resolve()
.then(() => (document.scrollingElement.scrollTop = bottom))
.then(
new Promise((resolve, reject) => {
let wait = setTimeout(() => {
clearTimeout(wait);
resolve();
}, 400);
})
)
.then(() => {
console.log(document.scrollingElement.scrollTop);
document.scrollingElement.scrollTop = currentScroll;
})
.then(
new Promise((resolve, reject) => {
let wait = setTimeout(() => {
clearTimeout(wait);
resolve();
}, 400);
})
)
.then(until(imagesHaveLoaded, 2000))
.then(Promise.all(promises));
它会加载延迟加载的图像,但是如果有更多延迟加载的图像将不起作用(我需要加载图像本身而不是url,这样我才能读取其数据)
答案 0 :(得分:1)
如果您想捕获加载到页面上的每个新图像,可以使用MutationObserver
这样的代码片段:
const targetNode = document.getElementById("root");
// Options for the observer (which mutations to observe)
let config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
if (mutation.addedNodes[0].tagName==="IMG") {
console.log("New Image added in DOM!");
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);