图片懒加载
最后更新于:2022-04-02 03:19:01
[TOC]
## jquery 实例
```
```
## 原生图片懒加载
方式一
```
var bodyScrollHeight = document.body.scrollTop;// body滚动高度
var windowHeight = window.innerHeight;// 视窗高度
var imgs = document.getElementsByClassName('lazyloadimg');
for (var i =0; i < imgs.length; i++) {
var imgHeight = imgs[i].offsetTop;// 图片距离顶部高度
if (imgHeight < windowHeight + bodyScrollHeight) {
imgs[i].src = imgs[i].getAttribute('data-src');
img[i].className = img[i].className.replace('lazyloadimg','')
}
}
}
```
方式二
```
//
function isVisible(el) {
const position = el.getBoundingClientRect()
const windowHeight = document.documentElement.clientHeight
// 顶部边缘可见
const topVisible = position.top > 0 && position.top < windowHeight;
// 底部边缘可见
const bottomVisible = position.bottom < windowHeight && position.bottom > 0;
return topVisible || bottomVisible;
}
function throttle(func, ms = 1000) {
let canRun = true
return function (...args) {
if (!canRun) return
canRun = false
setTimeout(() => {
func.apply(this, args)
canRun = true
}, ms)
}
}
function imageLazyLoad() {
const images = document.querySelectorAll('img')
for (let img of images) {
const realSrc = img.dataset.src
if (!realSrc) continue
if (isVisible(img)) {
img.src = realSrc
img.dataset.src = ''
}
}
}
// 测试
window.addEventListener('load', imageLazyLoad)
window.addEventListener('scroll', imageLazyLoad)
// or
window.addEventListener('scroll', throttle(imageLazyLoad, 1000))
```
';
