javascript - 加载页面上的所有图像并等待完成

标签 javascript dom browser google-chrome-extension lazy-loading

我试图加载页面上的所有图像(从 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));

它加载延迟加载图像,但如果有更多延迟加载图像,它将无法工作(我需要加载图像本身而不是网址,以便我可以读取它的数据)

最佳答案

如果您想捕获加载到页面的每个新图像,您可以使用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);

关于javascript - 加载页面上的所有图像并等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100501/

相关文章:

php - 建议制作在线编码竞赛网站的更好方法

javascript - 链接(或可链接的 DIV?)与背景图片 + 突出显示

javascript - 如何检查浏览器是否支持 css 值?

Javascript Date.now() 跨机器/时区的一致性

c# - Webbrowser 禁用所有音频输出 - 从在线广播到 youtube

javascript - Angularjs 中 View 之间的平移动画

javascript - 从 Javascript 中删除空行会提高性能吗?

html - Web 浏览器如何实现文本搜索?

JavaScript 以及为什么大写字母有时有效有时无效

javascript - 如何生成 <form :input> tags dynamically from JS?