通过监听scroll事件判断滚动位置,接近底部时触发加载;2. 使用防抖控制触发频率,避免性能问题;3. 设置isLoading状态防止重复请求;4. 添加加载中和已到底部提示提升用户体验。

实现无限滚动加载,核心是监听用户滚动行为,在接近页面底部时自动加载新内容。不需要复杂的框架,纯 HTML、CSS 和 JavaScript 就能完成。关键在于合理使用 scroll 事件监听 并控制触发频率,避免性能问题。
1. 监听滚动事件的基本结构
通过 addEventListener 绑定 window 的 scroll 事件,判断用户是否滚动到接近页面底部。
常用判断条件:
- 当前滚动位置 + 可视区高度 ≥ 整个文档高度 - 预设阈值
- 达标后触发加载函数
示例代码:
window.addEventListener('scroll', function() {
const scrollTop = window.pageYOffset;
const windowHeight = window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
const threshold = 100; // 距离底部100px时触发
if (scrollTop + windowHeight >= documentHeight - threshold) {
loadMoreData();
}
});
2. 防抖控制请求频率
scroll 事件触发非常频繁,不加控制会导致性能浪费甚至重复请求。使用防抖(debounce)机制,确保一定时间内只执行一次加载。
立即学习“前端免费学习笔记(深入)”;
简单防抖实现:
let scrollTimer = null;window.addEventListener('scroll', function() { if (scrollTimer) { clearTimeout(scrollTimer); } scrollTimer = setTimeout(() => { checkIfNearBottom(); }, 150); // 延迟150ms执行 });
function checkIfNearBottom() { const threshold = 100; const nearBottom = window.pageYOffset + window.innerHeight >= document.body.offsetHeight - threshold;
if (nearBottom && !isLoading) { loadMoreData(); } }
3. 添加加载状态防止重复请求
网络请求需要时间,必须设置标记位,避免用户快速滚动时多次触发加载。
- 定义 isLoading = false
- 开始请求前设为 true
- 数据加载完成后设为 false
示例逻辑:
let isLoading = false;function loadMoreData() { if (isLoading) return; isLoading = true;
// 模拟异步请求 fetch('/api/more-content') .then(res => res.json()) .then(data => { appendContent(data); isLoading = false; }) .catch(() => { isLoading = false; }); }
4. 提升体验:添加加载提示和结束提示
用户需要知道正在加载或已加载完毕。可以在页面底部插入提示元素。
- 显示“加载中...”动画
- 数据加载完隐藏提示
- 如果没有更多数据,显示“已到底部”
HTML 结构建议:
加载中...
基本上就这些,关键是控制好触发时机和请求节奏,避免卡顿和重复加载。










