性能优化方案
1.防抖与节流
场景
对于一些高频事件,可能在一段时间内有意识或者无意识的触发多次,而每一次的触发可能伴随着前后端交互,发送请求,这就给服务器造成很大的压力。
节流
思路:
- 节流一段时间只执行一次
- 针对最后一次,如果没到达设置的时间,则使用定时器延后执行
节流后的效果图如下

<body>
// dom结构
<input type="text" id="search">
// js代码
<script>
const dom = document.getElementById('search')
function querySearch(e) {
const value = e.target.value
console.log(value)
}
// 函数节流,一段时间只触发一次,最后一次一定触发
// 节流函数返回的还是一个函数
function throttle(fn, wait, options) {
let previous = 0 // 上一次的时间
let timer = null
function throttled(...arg) {
let context = this
let now = new Date()
let remaining = wait - (now - previous) // 剩余时间
if (remaining <=0) {
fn.apply(context, arg)
previous = now
clearInterval(timer)
timer = null
} else if (!timer){
timer = setTimeout(function() {
fn.apply(context, arg)
previous = now
}, remaining)
}
}
return throttled
}
dom.addEventListener('input', throttle(querySearch, 1000))
</script>
</body>
防抖
- 连续的点击,我们在一段时间后,只执行最后一次
- 思路每次执行判断是否有剩余时间,有剩余时间则把原来的定时器清除,在设置剩余时间后执行

防抖后的效果: 由图可以看出,我们只响应开始和结束,并且开始和结束都会延时一定的时间才执行
function debounce(fn, wait) {
let previous = 0
let timer = null
function debounced(...arg) {
let now = new Date()
let remaining = wait - (now - previous)
if (remaining > 0 && timer) { //有timer则清除定时器
clearInterval(timer)
timer = null
}
previous = now
timer = setTimeout(function() {
fn.apply(null, arg)
}, remaining)
}
return debounced
}
dom.addEventListener('input', debounce(querySearch, 1000))
2.前端监控
根据前端监控进行性能优化
- 性能监控
- 页面性能监控
- 页面静态资源的加载情况
- 异常监控
- ajax发送情况
- 页面错误
- 数据监控
- 用户的行为
性能监控
页面性能监控
- 利用浏览器performance这个API,算时间差


- Prompt for unload:浏览器准备卸载页面
- Redirect:导航栏跳转页面,缓存判断在这里进行,跨域一般为0
- App Cache:浏览器本地缓存处理
- DNS:dns解析、dns缓存,第一次比较慢,后面比较快
- TCP:http层面的握手、https层面的握手
- Request:http开始工作,发送请求。注意这里没有requestEnd,因为浏览器不知道啥时候传输结束
- unload:卸载页面
- response:接受请求结果。
- processing:
- domloading: dom开始加载
- domInteractive dom加载完成
- domContentLoaded:当前绑定的dom以及绑定的所有事件完成
- domComplete:整个页面资源加载完毕,触发onload事件
- onload:触发onload事件
- 接受:发送ajax(有跨域问题)或者使用Image(没有跨域问题)传递数据
页面静态资源监控
- 在window.onload()中使用window.performance.getEntriesByType('resource') // 获取页面静态资源的加载信息