以往我們想用圖片緩讀的話都會掛一隻 lazyload 的 js,現在 Chrome 宣布在版本 75 將有機會直接用 web 原生作照片緩讀的功能。
要用 web 原生的緩讀功能,只要加上 loading="lazy" 就好了,比如下面的寫法:
<img src="celebration.jpg" loading="lazy" alt="..." />
<iframe src="video-player.html" loading="lazy"></iframe>
loading 可以使用的屬性有以下幾種:
- lazy: 也就是照片緩讀
- eager: 不建議用這個,這也就是原本的瀏覽器行為
- auto: 讓瀏覽器去偵測要用哪一種方法
如果怕瀏覽器還沒支援,則可以使用以下方法去偵測是否要讀原本的那隻 lazyload 的外掛
if ('loading' in HTMLImageElement.prototype) {
// Browser supports `loading`..
} else {
// Fetch and apply a polyfill/JavaScript library
// for lazy-loading instead.
}
示範:
<pre class="brush: html"><!-- Let's load this in-viewport image normally -->
<img src="hero.jpg" alt=".."/>
<!-- Let's lazy-load the rest of these images -->
<img data-src="unicorn.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="cats.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="dogs.jpg" loading="lazy" alt=".." class="lazyload"/>
(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.
}
})();
參考:
Native image lazy-loading for the web!