做者:hateonionjavascript
https://hateonion.me/posts/19jan30/php
为何要作图片的懒加载
图片懒加载的原理

图片懒加载的简单实现
<!-- index.html --> <img src="placeholder.jpg" src="real_image.jpt" />
// index.css
img[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); })})()

图片懒加载的进阶实现–滚动加载
(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图片
图片尺寸已知
图片尺寸未知
懒加载防止布局抖动

<div class="lazy-load__container feature"> <img src="placeholder.jpg" src="real.jpg" /></div>
.lazy-load__container{ position: relative; display: block; height: 0;}
.lazy-load__container.feature { // feature image 的高宽比设置成42.8% // 对于其余图片 好比 post图片,高宽比可能会不一样,可使用其余css class去设置 padding-bottom: 42.8%;}
.lazy-load__container img { position: absolute; top:0; left:0; height: 100%; width: 100%;}

像Medium同样懒加载图片
-
使用 aspect ratio box 建立占位元素。 -
在html解析时只加载一个小尺寸的图片,而且添加blur效果。 -
最后使用js选择性的加载真实图片。
总结
-
懒加载用户当前视窗中的图片能够提高页面的加载性能。 -
懒加载的思路是在html解析时先加载一个placeholder图片,最后再用js选择性的加载真实图片。 -
若是须要滚动加载可使用 Intersection Observer 。 -
对于固定尺寸和不定尺寸的图片,咱们能够选择不一样的服务去或者placeholder图片。 -
对于图片尺寸不肯定引发的布局抖动问题咱们可使用 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
点个『在看』支持下 css
本文分享自微信公众号 - 前端技术江湖(bigerfe)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。html