是否有任何脚本可以延迟加载所有屏幕外图像?

问题描述 投票:0回答:1

我的网站有200多个页面,我不想手动修复每个页面。

我只想延迟加载屏幕外的图像。

是否可以自动完成任何脚本?

最诚挚的问候,

javascript performance pagespeed
1个回答
0
投票

下面的标记

<img src="myimage.jpg" loading="lazy" alt="..." />
<iframe src="content.html" loading="lazy"></iframe>

然后在JS文档中,创建一个配置对象,并在“ intersectionObserver”实例中注册它

const config = {
  rootMargin: '0px 0px 50px 0px',
  threshold: 0
};

// register the config object with an instance
// of intersectionObserver
let observer = new intersectionObserver(function(entries, self) {
  // iterate over each entry
  entries.forEach(entry => {
    // process just the images that are intersecting.
    // isIntersecting is a property exposed by the interface
    if(entry.isIntersecting) {
      // custom function that copies the path to the img
      // from data-src to src
      preloadImage(entry.target);
      // the image is now in place, stop watching
      self.unobserve(entry.target);
    }
  });
}, config);

您遍历所有图像并将它们添加到此“ iterationObserver”实例中

const imgs = document.querySelectorAll('[data-src]');
imgs.forEach(img => {
  observer.observe(img);
});

此解决方案的优点:实施起来轻而易举,有效,并且让“ intersectionObserver”在计算方面起了繁重的作用。

© www.soinside.com 2019 - 2024. All rights reserved.