前端性能优化
1.性能优化原则
- 多使用内存、缓存
- 减少CPU计算量,减少网络加载耗时
- 空间换时间
2.节流throttle
拖拽一个元素时,要随时拿到该元素被拖拽的位置
直接用drag事件,则会频繁触发,很容易导致卡顿
节流:无论拖拽速度多快,都会每隔100ms触发一次
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写节流throttle</title>
<style>
#div1 {
border: 1px solid #ccc;
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div id="div1" draggable="true">可拖拽</div>
<script>
const div1 = document.getElementById('div1')
// 1.节流使用
// let timer = null
// div1.addEventListener('drag', function (e) {
// if (timer) {
// return
// }
// timer = setTimeout(() => {
// console.log(e.offsetX, e.offsetY)
// timer = null
// }, 500)
// })
// 2.封装节流
function throttle(fn, delay = 100) {
let timer =null
return function () {
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
// 使用
div1.addEventListener('drag', throttle(function (e) {
console.log(e.offsetX, e.offsetY)
}, 100))
</script>
</body>
</html>
3.防抖debounce
监听一个输入框的,文字变化后触发change事件
直接用keyup事件,则会频繁触发change事件
防抖:用户输入结束或暂停时,才会触发change事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写防抖debounce</title>
</head>
<body>
<input type="text" id="input1">
<script>
const input1 = document.getElementById('input1')
// 1.防抖使用
// let timer = null
// input1.addEventListener('keyup', function () {
// if (timer) {
// clearTimeout(timer)
// }
// timer = setTimeout(() => {
// // 模拟触发 change事件
// console.log(input1.value)
// // 清空定时器
// timer = null
// }, 500)
// })
// 2.封装防抖
function debounce(fn, delay = 500) {
// timer 是闭包中的
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments) // arguments函数传的参
// fn() // 不传参写法
timer = null
}, delay)
}
}
// 使用
input1.addEventListener('keyup', debounce((arguments) => {
console.log(arguments)
console.log(input1.value)
}), 600)
</script>
</body>
</html>
4.图片懒加载
<img id="img1" src="xxx.png" data-realsrc="abc.png"/>
<script type="text/javascript>
var img1 = document.getElementById('img1')
img1.src = img1.getAttribute('data-realsrc')
</script>