随着浏览器性能的提升,前端也越来越关注用户体验,而影响用户体验其中一个很重要的指标便是受首屏渲染速度。我们常常会针对样式、脚本、图片、音频、视频等资源做处理,比如针对样式和脚本的压缩合并,将图片合并成雪碧图、将小图转化成base64、延迟加载等减少网络请求次数。现在大部分web应用含有大量的图片,对图片进行延迟加载无疑极大提升用户体验。以往我们可能会通过对比底部图片据可视区底部距离、窗口高度、滚动条距离来判断是否加载新图片,抑或在支持IntersectionObserver API的浏览器中使用交叉区观察者进行监听,而这都需要我们写脚本去判断及控制。今天给大家带来好消息是,Chrome 75 将原生支持图片的惰性加载,支持对img和iframe进行延迟加载,只需要将loading属性设置为lazy即可。<img src=“celebration.jpg” loading=“lazy” alt="…" /><iframe src=“video-player.html” loading=“lazy”></iframe>loading属性Loading属性控制浏览器是否延迟加载屏幕外的图像和iframe:lazy:对资源进行延迟加载。eager:立即加载资源。auto:浏览器自行判断决定是否延迟加载资源。默认效果(不设置该属性)和loading=auto的效果保持一致。需要注意的是,若浏览器决定该资源适合延迟加载,则需要避免页面不正常显示和影响用户体验。该loading属性支持img标签,无论img标签是否含有srcset属性及被picture标签包裹,以及iframe标签。示例代码:<!– Lazy-load an offscreen image when the user scrolls near it –><img src=“unicorn.jpg” loading=“lazy” alt=".."/><!– Load an image right away instead of lazy-loading –><img src=“unicorn.jpg” loading=“eager” alt=".."/><!– Browser decides whether or not to lazy-load the image –><img src=“unicorn.jpg” loading=“auto” alt=".."/><!– Lazy-load images in <picture>. <img> is the one driving image loading so <picture> and srcset fall off of that –><picture> <source media="(min-width: 40em)" srcset=“big.jpg 1x, big-hd.jpg 2x”> <source srcset=“small.jpg 1x, small-hd.jpg 2x”> <img src=“fallback.jpg” loading=“lazy”></picture><!– Lazy-load an image that has srcset specified –><img src=“small.jpg” srcset=“large.jpg 1024w, medium.jpg 640w, small.jpg 320w” sizes="(min-width: 36em) 33.3vw, 100vw" alt=“A rad wolf” loading=“lazy”><!– Lazy-load an offscreen iframe when the user scrolls near it –><iframe src=“video-player.html” loading=“lazy”></iframe>检测属性支持判断浏览器是否支持loading属性<script>if (’loading’ in HTMLImageElement.prototype) { // Browser supports loading..} else { // Fetch and apply a polyfill/JavaScript library // for lazy-loading instead.}</script>浏览器兼容一个新特性的出现必然无法立即兼容所有的浏览器,这需要我们结合以往的data-src进行懒加载的方式作向后兼容,而不是使用src、srcset、<source>,以避免不支持原生懒加载功能的浏览器对资源进行立即加载。<img loading=“lazy” data-src=“pic.png” class=“lazyload” alt="." />不支持原生懒加载的浏览器,我们使用lazySizes库进行兼容(async () => { if (’loading’ in HTMLImageElement.prototype) { const images = document.querySelectorAll(“img.lazyload”); images.forEach(img => { img.src = img.dataset.src; }); } else { // Dynamically import the LazySizes library const lazySizesLib = await import(’/lazysizes.min.js’); // Initiate LazySizes (reads data-src & class=lazyload) lazySizes.init(); // lazySizes works off a global. }})();请求细节原生懒加载在页面加载时获取前2KB的图像。如果服务器支持范围请求,则前2KB可能包含图像尺寸,这使我们能够生成/显示具有相同尺寸的占位符。当然前2KB也可能包括像图标这样的资产的整个图像。尝鲜在本篇文章发布时,chrome最新版本是73.0.3683.103,但我们可以通过启用浏览器的实验性功能开启这一特性。在chrome://flags页面搜索lazy,将Enable lazy image loading和Enable lazy frame loading设置为Enabled,重启浏览器即可。参考AddyOsmani.com - Native image lazy-loading for the web!Twitter - AddyOsmani 原帖欢迎关注公众号「前端新视界」获取前端技术前沿资讯,后台回复“1”领取100本PDF前端电子书籍。