Javascript 加载页面上的所有图像并等待完成
我试图加载页面上的所有图像(从chrome扩展端),然后在这些图像上执行一些代码,问题是有时站点会延迟加载图像(例如,当用户向下滚动到图像时) 有没有办法确保它们都已加载?我试着向下滚动到窗口底部,但分页不起作用Javascript 加载页面上的所有图像并等待完成,javascript,dom,browser,google-chrome-extension,lazy-loading,Javascript,Dom,Browser,Google Chrome Extension,Lazy Loading,我试图加载页面上的所有图像(从chrome扩展端),然后在这些图像上执行一些代码,问题是有时站点会延迟加载图像(例如,当用户向下滚动到图像时) 有没有办法确保它们都已加载?我试着向下滚动到窗口底部,但分页不起作用 export function imagesHaveLoaded() { return Array.from(document.querySelectorAll("img")).every(img => img.complete && img.naturalW
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,以便我可以读取它的数据)如果您想捕获加载到页面的每个新图像,可以使用
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);
但我如何才能使图像加载在第一位?我是否需要以某种方式使其不断向下滚动?您需要将滚动和处理分开:首先滚动,然后在setTimeout或MutationObserver回调中处理。另外,请使用document.scrollingElement。