【问题标题】:Load all images on page and wait till done加载页面上的所有图像并等待完成
【发布时间】:2019-09-29 17:09:23
【问题描述】:

我正在尝试加载页面上的所有图像(从 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,以便我可以读取它的数据)

【问题讨论】:

  • 但是我怎样才能让图像首先加载呢?我不需要以某种方式使其不断向下滚动吗?
  • 您需要将滚动和处理分开:首先滚动,然后在 setTimeout 或 MutationObserver 回调中处理。另外,使用 document.scrollingElement.

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


【解决方案1】:

如果你想捕捉加载到页面的每一个新图像,你可以使用MutationObserver 像这样的代码 sn-p:

    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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多