延迟加载图像以提高网站性能的五种方法

图像和iframe的本机延迟加载非常酷。没有什么比下面的标记更直接了:

...

如您所见,没有JavaScript,没有src属性值的动态交换,只是普通的旧HTML。

该loading属性使我们可以选择延迟屏幕外图像和iframe,直到用户滚动到页面上的位置为止。loading可以采用以下三个值之一:

lazy:非常适合延迟加载
eager:指示浏览器立即加载指定的内容
auto:保留延迟加载或不延迟加载到浏览器的选项。
这种方法无可匹敌:它的开销为零,简洁明了。但是,尽管在撰写本文时,大多数主流浏览器都对该loading属性提供了良好的支持,但并不是所有浏览器都支持该特性。

要获得有关此令人敬畏的延迟加载图像功能的深入文章,包括浏览器支持的解决方法,请不要错过Addy Osmani的“ Web的本地图像延迟加载!”。

#2使用Intersection Observer API的延迟加载
该路口观察API是一个现代化的界面,你可以利用的延迟加载图片和其他内容。

MDN引入此API的方法如下:

Intersection Observer API提供了一种异步观察目标元素与祖先元素或顶级文档的视口相交的变化的方法。


如果所有网站中有35%是WordPress,PHP真的那么死了吗?

免费获取“ PHP和MySQL:Ninja的新手,第六版”。

找到更多
换句话说,异步监视的是一个元素与另一个元素的交集。

Denys Mishunov在“相交观察器”和使用它的延迟加载图像方面都有很好的教程。这就是他的解决方案。

假设您要延迟加载图片库。每个图像的标记如下所示:

test image
请注意,图像的路径是如何包含在data-src属性(而不是src属性)中的。原因是使用src意味着图像将立即加载,这不是您想要的。

在CSS中,为每个图像赋予一个min-height值,例如100px。这为每个图像占位符(不带src属性的img元素)提供了一个垂直尺寸:

img {
  min-height: 100px;
  /* more styles here */
}
然后,在JavaScript文档中,创建一个config对象并将其注册到intersectionObserver实例:

// create config object: rootMargin and threshold
// are two properties exposed by the interface
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在计算方面做得很繁重。

你可能感兴趣的:(延迟加载图像以提高网站性能的五种方法)