圖片懶加載從簡單到復(fù)雜

作者 | hateonion
來源 | https://hateonion.me/posts/19jan30/
為什么要做圖片的懶加載
圖片懶加載的原理

圖片懶加載的簡單實(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
??愛心三連擊
1.看到這里了就點(diǎn)個(gè)在看支持下吧,你的「點(diǎn)贊,在看」是我創(chuàng)作的動(dòng)力。
2.關(guān)注公眾號(hào)
程序員成長指北,回復(fù)「1」加入Node進(jìn)階交流群!「在這里有好多 Node 開發(fā)者,會(huì)討論 Node 知識(shí),互相學(xué)習(xí)」!3.也可添加微信【ikoala520】,一起成長。
“在看轉(zhuǎn)發(fā)”是最大的支持
評(píng)論
圖片
表情
