js实现加载更多内容
实现滚动加载更多内容
滚动加载是一种常见的分页加载方式,通过监听滚动事件判断是否到达页面底部触发加载。
window.addEventListener('scroll', function() {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
loadMoreContent();
}
});
function loadMoreContent() {
// 防止重复加载
if (isLoading) return;
isLoading = true;
fetch('/api/items?page=' + currentPage)
.then(response => response.json())
.then(data => {
currentPage++;
renderItems(data);
isLoading = false;
});
}
使用Intersection Observer API
现代浏览器推荐使用Intersection Observer API实现懒加载,性能优于滚动事件监听。

const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreContent();
}
});
// 观察页面底部元素
const sentinel = document.querySelector('#load-more-sentinel');
observer.observe(sentinel);
function loadMoreContent() {
fetch('/api/items?page=' + currentPage)
.then(response => response.json())
.then(data => {
if (data.length === 0) {
observer.unobserve(sentinel);
return;
}
currentPage++;
renderItems(data);
});
}
按钮点击加载更多
通过用户主动点击按钮触发内容加载,适合需要明确用户意图的场景。

<button id="load-more-btn">加载更多</button>
<div id="content-container"></div>
document.getElementById('load-more-btn').addEventListener('click', loadMoreContent);
function loadMoreContent() {
fetch('/api/items?page=' + currentPage)
.then(response => response.json())
.then(data => {
if (data.length === 0) {
document.getElementById('load-more-btn').disabled = true;
return;
}
currentPage++;
renderItems(data);
});
}
实现无限滚动列表
对于大型列表,可以使用虚拟滚动技术优化性能,仅渲染可视区域内的元素。
class InfiniteScroll {
constructor(container, itemHeight, renderItem) {
this.container = container;
this.itemHeight = itemHeight;
this.renderItem = renderItem;
this.data = [];
this.visibleItems = [];
this.startIndex = 0;
this.init();
}
init() {
this.container.style.height = `${window.innerHeight}px`;
this.container.style.overflow = 'auto';
this.container.addEventListener('scroll', () => {
this.handleScroll();
});
this.loadData();
}
handleScroll() {
const scrollTop = this.container.scrollTop;
const newStartIndex = Math.floor(scrollTop / this.itemHeight);
if (newStartIndex !== this.startIndex) {
this.startIndex = newStartIndex;
this.renderVisibleItems();
}
}
renderVisibleItems() {
// 仅渲染可视区域内的元素
}
loadData() {
// 获取新数据并更新列表
}
}
性能优化建议
实现加载更多功能时需注意性能优化,避免不必要的渲染和请求。
- 使用防抖函数限制滚动事件触发频率
- 添加加载状态指示器避免重复请求
- 实现数据缓存减少服务器请求
- 对于大量数据考虑虚拟滚动技术
- 添加错误处理机制应对网络问题
// 防抖函数示例
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), delay);
};
}
window.addEventListener('scroll', debounce(() => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
loadMoreContent();
}
}, 200));






