前端性能优化:利用闭包节流实现图片懒加载
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片懒加载title>
head>
<style>
img{
display: block;
width: 300px;
height: 300px;
margin: 30px auto;
}
style>
<body>
<h1>图片懒加载h1>
<img data-src="./img/1.jpeg" src="">
<img data-src="./img/2.jpeg" src="">
<img data-src="./img/3.jpeg" src="">
<img data-src="./img/4.jpeg" src="">
<img data-src="./img/5.jpeg" src="">
<img data-src="./img/6.jpeg" src="">
<img data-src="./img/7.jpeg" src="">
<img data-src="./img/8.jpeg" src="">
<img data-src="./img/9.jpeg" src="">
<script>
let img = document.getElementsByTagName('img')
let _clientHeight = document.documentElement.clientHeight
let _scrollTop = document.documentElement.scrollTop || document.body.scrollTop
let imgLength = img.length
let currentLoad = 0
let isLoadImg = false
function computedClientHeight() {
_clientHeight = document.documentElement.clientHeight
console.log('_clientHeight',_clientHeight)
}
function lazyLoad() {
isLoadImg = currentLoad >= imgLength
console.log('isLoadImg',isLoadImg)
if (!isLoadImg){
console.log('执行懒加载')
_scrollTop = document.documentElement.scrollTop || document.body.scrollTop
for (let i = currentLoad;i<imgLength;i++){
if (img[i].offsetTop<_clientHeight+_scrollTop){
if (img[i].getAttribute('src') ===''){
img[i].src = img[i].getAttribute('data-src')
}
currentLoad = i+1
}
}
}
}
lazyLoad();
function throttle(func,wait){
let timer
return ()=>{
if (isLoadImg){
return
}
if (!timer){
console.log('执行节流')
timer = setTimeout(()=>{
func()
clearTimeout(timer)
timer = null
},wait)
}
}
}
function debounce(callback,delay) {
let timer
return (value=null)=>{
clearTimeout(timer)
if (isLoadImg){
return
}
timer = setTimeout(()=>{
console.log('防抖执行')
callback(value);
},delay)
}
}
window.addEventListener('scroll',throttle(lazyLoad,100))
window.addEventListener('resize',debounce(computedClientHeight,800))
script>
body>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103