浏览器原生支持lazyload图片的二三事

看了下 WordPress 更新日志,发现新增了lazy-loading功能。我好奇该功能是如何实现的,经查才发现浏览器已经原生支持 lazyload 懒加载了。

起因

懒加载的效果是当窗口滑动到该位置时,才加载此媒体资源,以节省网络流量。

大多数插件的原理:新增自定义属性保存真实媒体资源路径,当该元素可视时,把 src 地址换成真实地址。

而在 WordPress 更新日志中,我发现了这样一行内容:

In WordPress 5.5, images wait to load until they are just about to scroll into view. The technical term is lazy loading.

我查看了 WordPress 的懒加载,发现其并没有引入第三方插件,也没有修改标签的媒体文件链接,仅仅是给 img 标签添加了loading="lazy"

关于 loading 属性

Web.dev 上这样说:

Chrome and Firefox both support native browser lazy-loading with the loading attribute. This attribute can be added to <img> elements, and also to <iframe> elements. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them.

在 MDN 上,img 的 laoding 属性描述如下:

  • loading
    Indicates how the browser should load the image:

    • eager: Loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value).
    • lazy: Defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it’s reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases.

MDN 浏览器兼容性列表里显示,除了果子全家和 IE,以及某些低版本的浏览器外,大家都支持该属性。

我火星了。

WordPress 触发时机

当一个 img 标签同时具有 widthheight属性时,WordPress 的过滤器才会为其添加loading="lazy"

举个例子:

<img src="//up-free-imgs.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg">
<img src="//up-free-imgs.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg" width="100%">
<img src="//up-free-imgs.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg" width="100%" height="auto">

经新版 WordPress 处理后:

<!-- output -->
<img src="//pic-cdn.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg">
<img src="//pic-cdn.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg" width="100%">
<img loading="lazy" src="//pic-cdn.azimiao.com/wp-content/uploads/2020/09/FlightSimulator_4.jpg" width="100%" height="auto">

优点

浏览器原生支持该属性,完美解决了一些人的纠结心态:百度到底会不会运行我的js 插件代码来抓取真实图像?

现在有了它,媒体文件的路径不会发生改变,也就不用担心 SEO 的问题了。

你火星了没?

梓喵出没博客(azimiao.com)版权所有,转载请注明链接:https://www.azimiao.com/7181.html
欢迎加入梓喵出没博客交流群:313732000

我来吐槽

*

*

0位绅士参与评论

  1. 大致09-27 12:06 回复

    也就是说,自己加图片的时候加上loading=“lazy”就可以无视WP版本了呗。
    另外百度不抓不是好事吗?