圖片懶加載從簡(jiǎn)單到復(fù)雜
(給全棧前端精選加星標(biāo),提升前端技能)
作者:hateonion
https://hateonion.me/posts/19jan30/
為什么要做圖片的懶加載
圖片懶加載的原理

圖片懶加載的簡(jiǎn)單實(shí)現(xiàn)
// index.cssimg[src] {filter: blur(0.2em);}img {filter: blur(0em);transition: filter 0.5s;}
(function lazyLoad(){const imageToLazy = document.querySelectorAll('img[src]');const loadImage = function (image) {image.setAttribute('src', image.getAttribute('src'));image.addEventListener('load', function() {image.removeAttribute("src");})}imageToLazy.forEach(function(image){loadImage(image);})})()

圖片懶加載的進(jìn)階實(shí)現(xiàn)–滾動(dòng)加載
(function lazyLoad(){const imageToLazy = document.querySelectorAll('img[src]');const loadImage = function (image) {image.setAttribute('src', image.getAttribute('src'));image.addEventListener('load', function() {image.removeAttribute("src");})}const intersectionObserver = new IntersectionObserver(function(items, observer) {items.forEach(function(item) {if(item.isIntersecting) {loadImage(item.target);observer.unobserve(item.target);}});});imageToLazy.forEach(function(image){intersectionObserver.observe(image);})})()
如何選擇合適的Placeholder圖片
圖片尺寸已知
圖片尺寸未知
懶加載防止布局抖動(dòng)

.lazy-load__container{position: relative;display: block;height: 0;}.lazy-load__container.feature {// feature image 的高寬比設(shè)置成42.8%// 對(duì)于其他圖片 比如 post圖片,高寬比可能會(huì)不同,可以使用其他css class去設(shè)置padding-bottom: 42.8%;}.lazy-load__container img {position: absolute;top:0;left:0;height: 100%;width: 100%;}

像Medium一樣懶加載圖片
使用 aspect ratio box 創(chuàng)建占位元素。 在html解析時(shí)只加載一個(gè)小尺寸的圖片,并且添加blur效果。 最后使用js選擇性的加載真實(shí)圖片。
總結(jié)
懶加載用戶當(dāng)前視窗中的圖片可以提升頁面的加載性能。 懶加載的思路是在html解析時(shí)先加載一個(gè)placeholder圖片,最后再用js選擇性的加載真實(shí)圖片。 如果需要滾動(dòng)加載可以使用 Intersection Observer 。 對(duì)于固定尺寸和不定尺寸的圖片,我們可以選擇不同的服務(wù)去或者placeholder圖片。 對(duì)于圖片尺寸不確定引起的布局抖動(dòng)問題我們可以使用 aspect ratio box 來解決。
參考資料
Progressive Loading Lazy loading with responsive images and unknown height Simple image placeholders for lazy loading images How Medium does progressive image loading Sizing Fluid Image Containers with a Little CSS Padding Hack
評(píng)論
圖片
表情
