使用 lazysizes 延迟加载屏幕外图像

Appears in: 快速加载

延迟加载是一种进行等待直到需要资源时才进行加载的方法,而不是提前加载资源。这可以减少初始页面加载时需要加载和解析的资源量,从而提高性能。

在初始页面加载期间屏幕外的图像是此技术的理想候选者。最重要的是,lazysizes 让该技术成为非常简单的实现策略。

将 lazysizes 脚本添加到页面 #

  • Click Remix to Edit to make the project editable.

lazysizes.min.js 已被下载并添加到该 Glitch 中。要将其包含在页面中:

  • 将以下 <script> 标签添加到 index.html
  <script src="lazysizes.min.js" async></script>
<!-- Images End -->
</body>

当用户滚动页面时,lazysizes 将智能地加载图像,并优先考虑用户即将浏览到的图像。

指示要延迟加载的图像 #

  • lazyload 类添加到应延迟加载的图像中。此外,将 src 属性改为 data-src

例如,对 flower3.png 的更改如下所示:

<img src="images/flower3.png" alt="">
<img data-src="images/flower3.png" class="lazyload" alt="">

对于此示例,请尝试延迟加载 flower3.pngflower4.jpgflower5.jpg

实现方式 #

就是这样!要查看这些更改的实际效果,请按照以下步骤操作:

  • To preview the site, press View App. Then press Fullscreen fullscreen.

  • 打开控制台,找到刚刚添加的图像。当您向下滚动页面时,它们的类应该从 lazyload 改变为 lazyloaded

延迟加载的图像
  • 向下滚动页面时,注视网络面板,可以看到图像文件逐个添加。
延迟加载的图像

使用 Lighthouse 进行验证 #

最后,最好使用 Lighthouse 来验证这些更改。Lighthouse 的“延迟屏幕外图像”性能审核将提醒您是否忘记了向任何屏幕外图像添加延迟加载。

  1. To preview the site, press View App. Then press Fullscreen fullscreen. 1. Press `Control+Shift+J` (or `Command+Option+J` on Mac) to open DevTools.

  2. Click the Lighthouse tab.

  3. Make sure the Performance checkbox is selected in the Categories list.

  4. Click the Generate report button.

  5. 验证延迟屏幕外图像审核已通过。

在 Lighthouse 中'通过有效编码图像'审核

成功!您已使用 lazysizes 延迟加载了您页面上的图像。

Last updated: Improve article
By Chrome DevRel