压缩原始图片
-
将原始图片压缩至1~2kb甚至更小的图片
nature.jpg - 压缩 java 图片压缩
nature1.jpg -
添加高斯模糊
natureBlur.png -
效果
interview.gif
加载顺序
- 展示压缩后的图片添加高斯模糊,随页面加载而加载
- 页面load完成之后,开始加载原始图片
- 原始图片加载完成之后,替换掉预览的压缩图片
源码
- html
<div>
<!-- 图片未加载完成时可以通过a标签浏览-->
<a href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/nature5.jpg">
<img style="width:800px;height:200px"
class="lazy-img"
src="../assets/nature.jpg"
data-original="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/nature5.jpg"
alt="">
</a>
</div>
- js
function lazyLoad () {
const imgs = document.getElementsByClassName('lazy-img')
let img = new Image()
const oldImg = imgs[0]
img.src = oldImg.getAttribute('data-original')
img.classList.add('real-img')
let replaceImg = function () {
const c = oldImg.parentElement
c.removeAttribute('href')
c.appendChild(img)
c.removeChild(oldImg)
}
const replace = function () {
requestAnimationFrame(replaceImg)
}
if (img.complete)
replace()
else
img.onload = replace
},
window.addEventListener('load', () => {
lazyLoad()
})
- css
img:not(.lazy-img) {
will-change: transform opacity;
width: 800px;
height: 200px;
animation: realImg 0.5s linear;
}
@keyframes realImg {
0% {
filter: blur(15px);
}
100% {
filter: blur(0);
}
}
.lazy-img {
filter: blur(15px);
}
网友评论