js实现上拉加载
实现上拉加载的基本思路
监听滚动事件,当滚动到接近底部时触发数据加载。需要计算滚动位置、容器高度和滚动条位置的关系。
监听滚动事件
在需要实现上拉加载的容器上添加滚动事件监听:
const container = document.getElementById('scroll-container');
container.addEventListener('scroll', handleScroll);
判断是否滚动到底部
滚动事件处理函数中判断是否到达底部:
function handleScroll() {
const scrollTop = container.scrollTop;
const scrollHeight = container.scrollHeight;
const clientHeight = container.clientHeight;
if (scrollTop + clientHeight >= scrollHeight - 50) {
loadMoreData();
}
}
加载数据函数
实现数据加载的函数,可以是API请求或其他数据获取方式:
function loadMoreData() {
if (isLoading) return;
isLoading = true;
showLoadingIndicator();
fetch('/api/data?page=' + currentPage)
.then(response => response.json())
.then(data => {
appendData(data);
currentPage++;
isLoading = false;
hideLoadingIndicator();
});
}
优化性能
使用防抖或节流避免频繁触发滚动事件:
const throttledHandleScroll = throttle(handleScroll, 200);
container.addEventListener('scroll', throttledScroll);
function throttle(func, limit) {
let inThrottle;
return function() {
if (!inThrottle) {
func.apply(this, arguments);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
完整示例代码
let currentPage = 1;
let isLoading = false;
const container = document.getElementById('scroll-container');
container.addEventListener('scroll', throttle(handleScroll, 200));
function handleScroll() {
const { scrollTop, scrollHeight, clientHeight } = container;
if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading) {
loadMoreData();
}
}
async function loadMoreData() {
isLoading = true;
showLoadingIndicator();
try {
const response = await fetch(`/api/data?page=${currentPage}`);
const data = await response.json();
appendData(data);
currentPage++;
} catch (error) {
console.error('Error loading data:', error);
} finally {
isLoading = false;
hideLoadingIndicator();
}
}
注意事项
确保在数据加载完成前不会重复触发加载 在无更多数据可加载时应移除滚动监听 移动端需要考虑触摸事件的兼容性 对于无限滚动列表,建议使用虚拟滚动技术优化性能







