1. 防抖
防抖技术可以防止短时间内多次触发同一请求。
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const debouncedFetch = debounce(fetchData, 300);
debouncedFetch('https://api.example.com/data');
使用场景
- 搜索输入框:用户在输入时,连续触发
keyup
事件,只有在输入结束后才发送请求。 - 窗口调整:用户调整浏览器窗口大小时,频繁触发
resize
事件。防抖可以确保调整结束后再执行相应操作。 - 表单验证:用户输入表单数据时,可以用防抖来减少频繁的验证请求。
2.节流
节流技术可以限制请求的频率,确保在一定时间内只执行一次请求。
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const throttledFetch = throttle(fetchData, 1000);
throttledFetch('https://api.example.com/data');
使用场景
- 页面滚动:用户滚动页面时触发
scroll
事件,使用节流限制处理函数的执行频率。 - 按钮点击:防止用户短时间内多次点击同一个按钮,造成重复提交。
- 游戏动画:限制每秒渲染的帧数,以减少资源消耗。
3.使用缓存
使用缓存
通过缓存机制避免重复请求相同的资源或数据。
-
HTTP 缓存:设置
Cache-Control
和Expires
头,让浏览器缓存资源。 -
本地缓存:使用
localStorage
或sessionStorage
缓存数据。
// 使用 localStorage 缓存数据
function fetchData(url) {
const cachedData = localStorage.getItem(url);
if (cachedData) {
return Promise.resolve(JSON.parse(cachedData));
}
return fetch(url)
.then(response => response.json())
.then(data => {
localStorage.setItem(url, JSON.stringify(data));
return data;
});
}
4.管理请求状态
在大型应用中使用状态管理库(如 Redux、Vuex)管理请求状态,避免重复请求。
// 使用 Redux 管理请求状态
const fetchData = (url) => (dispatch, getState) => {
const { data } = getState();
if (data[url]) {
return;
}
dispatch({ type: 'FETCH_DATA_REQUEST', url });
fetch(url)
.then(response => response.json())
.then(data => dispatch({ type: 'FETCH_DATA_SUCCESS', url, data }))
.catch(error => dispatch({ type: 'FETCH_DATA_FAILURE', url, error }));
};