js实现上拉加载
实现上拉加载的基本思路
监听滚动事件,判断是否滚动到页面底部。当滚动到底部时触发加载更多数据的操作。
监听滚动事件
window.addEventListener('scroll', function() {
// 判断是否滚动到底部
});
判断滚动到底部的条件
需要比较三个值:
- 滚动条距离顶部的距离(scrollTop)
- 可视区域高度(clientHeight)
- 页面总高度(scrollHeight)
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const clientHeight = document.documentElement.clientHeight;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + clientHeight >= scrollHeight - 10) {
// 触发加载更多
}
加载数据的实现
let isLoading = false;
let currentPage = 1;
function loadMore() {
if (isLoading) return;
isLoading = true;
// 显示加载中提示
showLoadingIndicator();
fetch(`/api/data?page=${currentPage}`)
.then(response => response.json())
.then(data => {
// 处理新数据
renderData(data);
currentPage++;
isLoading = false;
// 隐藏加载中提示
hideLoadingIndicator();
})
.catch(error => {
isLoading = false;
// 隐藏加载中提示
hideLoadingIndicator();
});
}
优化性能
使用节流函数减少滚动事件的触发频率:
function throttle(fn, delay) {
let timer = null;
return function() {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
};
}
window.addEventListener('scroll', throttle(checkScroll, 200));
完整示例代码
let isLoading = false;
let currentPage = 1;
function checkScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const clientHeight = document.documentElement.clientHeight;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + clientHeight >= scrollHeight - 10 && !isLoading) {
loadMore();
}
}
function loadMore() {
isLoading = true;
showLoadingIndicator();
fetch(`/api/data?page=${currentPage}`)
.then(response => response.json())
.then(data => {
renderData(data);
currentPage++;
isLoading = false;
hideLoadingIndicator();
})
.catch(error => {
isLoading = false;
hideLoadingIndicator();
});
}
function throttle(fn, delay) {
let timer = null;
return function() {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
};
}
window.addEventListener('scroll', throttle(checkScroll, 200));
注意事项
- 确保在加载完成前不会重复触发加载
- 处理网络请求失败的情况
- 当没有更多数据时需要显示提示或禁用加载
- 移动端需要考虑touch事件和滚动性能优化







