js 加载更多实现
滚动监听实现加载更多
通过监听滚动事件,判断是否滚动到页面底部触发加载。核心是计算scrollTop、clientHeight和scrollHeight的关系:
window.addEventListener('scroll', function() {
const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5) {
loadMoreData();
}
});
function loadMoreData() {
// 获取数据并渲染到页面
}
Intersection Observer API实现
现代浏览器推荐使用Intersection Observer API,性能更好:

const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreData();
}
});
const sentinel = document.createElement('div');
sentinel.id = 'sentinel';
document.body.appendChild(sentinel);
observer.observe(sentinel);
分页参数控制
后端API通常需要分页参数控制数据获取:

let currentPage = 1;
const pageSize = 10;
async function loadMoreData() {
const data = await fetch(`/api/data?page=${currentPage}&size=${pageSize}`);
currentPage++;
renderData(data);
}
加载状态管理
避免重复请求需要管理加载状态:
let isLoading = false;
async function loadMoreData() {
if (isLoading) return;
isLoading = true;
showLoadingIndicator();
try {
const data = await fetchData();
renderData(data);
} finally {
isLoading = false;
hideLoadingIndicator();
}
}
虚拟滚动优化
对于大量数据,考虑虚拟滚动技术:
// 使用库如react-window或vue-virtual-scroller
import { FixedSizeList as List } from 'react-window';
<List
height={500}
itemCount={1000}
itemSize={50}
width={300}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</List>






