网站性能优化
- 我们在执行鼠标移动事件时,触发事件的频率非常的快,这样的执行方式会让我们的网页出现卡顿的现象。用得比较多的地方是当我们快抢或发送Ajax请求时,如果没有优化懂一点技术的人就会使用恶意脚本对后台提交数据。
- 节流:在同一时间内,只能触发一次函数
html
<body>
<div id="text">0</div>
<button id="btn">click</button>
</body>
js
var text = document.getElementById("text");
var btn = document.getElementById("btn");
btn.onclick = throttle(add, 1000)
function add() {
text.innerText = parseInt(text.innerText) + 1;
}
function throttle(fn, wait) {
var lastTime = 0;
return function() {
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
fn();
lastTime = nowTime;
}
}
}
3.防抖: 事件触发以后,隔一段事件再次触发
html
<body>
<input type="text" name="" id="ins">
</body>
js
var input = document.getElementById("ins");
var timer = null;
input.oninput = function() {
clearTimeout(timer);
timer = setTimeout(function() {
ajax()
}, 1000)
}
function ajax() {
console.log(input.value);
}