使用 Chrome 原生 lazyload 屬性進行圖片懶載入
在最近的 OAdF&index=5&t=0s" rel="nofollow,noindex" target="_blank">《Chrome Dev Summit - Key Techniques for Fast Websites》 ,Chrome 團隊的成員介紹了,原生的 lazyload
屬性即將登陸 Chrome。
一聽到 lazyload ,大家可能印象最深的是就是早期瀑布流 Pinterest 網站的的載入效果。效果如下;
實現效果可以參考很早之前寫的關於圖片的 placeholder 《實現類似Pinterest 的圖片預載入功能》 。這是我們需要通過 JS 來進行一些圖片的載入和替換。很開心,Chrome 給了大家嚐鮮這個屬性的機會,我們在 W3C 的草案中,很早就可以看到對於這個屬性的定義;
The lazyload attribute is a boolean and IDL attribute that indicates the priority order in which the User Agent should download the resource associated with the element in cases of network resource contention.
當然這個還是一個實驗性的屬性,因此你需要手動在 Chrome 輸入
chrome://flags/#enable-lazy-image-loading
進行開啟。
lazyload 支援三種賦值,類似於 preload
。
auto on off
我們可以通過實驗效果來看下官方的 lazyload 的效果
從效果上看,確實我們可以看到預佔位了一張圖片,然後使用者在滾動觸發載入,不過感覺 UI 效果並不會太滿足要求。不過 lazyload 還支援 iframe
,因此一些嵌入 iframe 的站點可以嘗試使用。當然這還是一個實驗性屬性,因此不要期待在 Safari 或者 Firefox 也能工作。