js 加载更多实现
滚动监听实现加载更多
通过监听滚动事件判断是否到达页面底部触发加载。核心逻辑是计算滚动条位置与文档高度的关系。
window.addEventListener('scroll', function() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight;
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight - 100) {
loadMoreData();
}
});
function loadMoreData() {
// 获取新数据并渲染到页面
}
Intersection Observer API
现代浏览器推荐使用的API,性能优于滚动监听。通过观察目标元素与视口的交叉状态触发回调。

const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreData();
}
}, {threshold: 0.1});
observer.observe(document.querySelector('#load-more-trigger'));
分页加载实现
配合后端API实现分页加载,通常需要维护当前页码或游标。

let currentPage = 1;
const pageSize = 10;
async function loadMoreData() {
const response = await fetch(`/api/data?page=${currentPage}&size=${pageSize}`);
const newData = await response.json();
renderData(newData);
currentPage++;
if (newData.length < pageSize) {
removeLoadMoreTrigger();
}
}
虚拟滚动优化
对于超长列表建议使用虚拟滚动技术,只渲染可视区域内的元素。
// 使用现有库如react-window或vue-virtual-scroller
import { FixedSizeList } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const List = () => (
<FixedSizeList
height={600}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</FixedSizeList>
);
加载状态处理
添加加载状态避免重复请求和改善用户体验。
let isLoading = false;
async function loadMoreData() {
if (isLoading) return;
isLoading = true;
showLoadingIndicator();
try {
const data = await fetchData();
renderData(data);
} catch (error) {
showError(error);
} finally {
isLoading = false;
hideLoadingIndicator();
}
}
无限滚动注意事项
- 移动端需要考虑滚动性能优化
- 需要提供回到顶部按钮
- 数据量过大时应考虑分页或搜索过滤
- 注意内存管理,避免长时间运行导致内存泄漏






