js实现滚动加载
滚动加载的实现方法
滚动加载(Infinite Scroll)是一种常见的前端技术,通过监听滚动事件动态加载更多内容。以下是几种实现方式:
监听滚动事件 通过监听窗口或容器的滚动事件,判断是否滚动到底部触发加载:
window.addEventListener('scroll', function() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
if (scrollTop + windowHeight >= documentHeight - 100) {
loadMoreData();
}
});
Intersection Observer API 现代浏览器推荐使用Intersection Observer API,性能更好:
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreData();
}
});
const sentinel = document.querySelector('#load-more-trigger');
observer.observe(sentinel);
实现注意事项
- 节流处理:滚动事件需要节流,避免频繁触发
- 加载状态:需要设置加载状态,防止重复请求
- 错误处理:网络请求需要错误处理和重试机制
- 移动端适配:需要考虑移动端触摸滚动特性
完整示例代码

let isLoading = false;
let currentPage = 1;
async function loadMoreData() {
if (isLoading) return;
isLoading = true;
try {
const data = await fetch(`/api/data?page=${currentPage}`);
renderData(data);
currentPage++;
} catch (error) {
console.error('加载失败', error);
} finally {
isLoading = false;
}
}
// 使用Intersection Observer
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !isLoading) {
loadMoreData();
}
}, {threshold: 0.1});
observer.observe(document.querySelector('#load-more-trigger'));
性能优化建议
- 使用虚拟列表技术处理大量数据
- 考虑使用骨架屏提升用户体验
- 实现提前加载,避免用户看到空白
- 移动端注意滚动性能优化
以上方法可以根据具体项目需求选择或组合使用。现代前端框架如React、Vue等也有相应的无限滚动组件可供选择。






