js实现加载更多内容
实现滚动加载更多内容
使用Intersection Observer API监听元素是否进入视口,触发加载更多操作。这种方法性能较好,避免频繁计算滚动位置。
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadMoreContent();
}
});
});
const sentinel = document.querySelector('#load-more-trigger');
observer.observe(sentinel);
function loadMoreContent() {
// 获取新内容逻辑
fetch('/api/load-more')
.then(response => response.json())
.then(data => {
// 将新内容插入DOM
const container = document.querySelector('#content-container');
data.items.forEach(item => {
container.appendChild(createItemElement(item));
});
});
}
按钮点击加载更多
实现一个简单的点击加载更多按钮的方案,适合基础需求。

document.querySelector('#load-more-btn').addEventListener('click', () => {
const currentPage = parseInt(btn.dataset.page) || 1;
fetch(`/api/items?page=${currentPage + 1}`)
.then(response => response.json())
.then(data => {
if (data.items.length) {
btn.dataset.page = currentPage + 1;
renderItems(data.items);
} else {
btn.disabled = true;
btn.textContent = '没有更多内容';
}
});
});
function renderItems(items) {
const container = document.querySelector('#items-container');
items.forEach(item => {
container.appendChild(createItemElement(item));
});
}
无限滚动实现
结合滚动事件和节流函数实现传统无限滚动方案。

let isLoading = false;
window.addEventListener('scroll', throttle(() => {
const scrollPosition = window.scrollY + window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
if (scrollPosition >= documentHeight - 300 && !isLoading) {
isLoading = true;
document.querySelector('#loading-indicator').style.display = 'block';
fetchMoreData()
.then(data => {
appendData(data);
isLoading = false;
document.querySelector('#loading-indicator').style.display = 'none';
});
}
}, 200));
function fetchMoreData() {
return fetch('/api/more-data').then(res => res.json());
}
分页加载优化
实现带分页的加载更多功能,包含错误处理和加载状态。
let currentPage = 1;
const pageSize = 10;
async function loadMore() {
try {
showLoading();
const response = await fetch(`/api/data?page=${currentPage}&size=${pageSize}`);
const newData = await response.json();
if (newData.length) {
renderData(newData);
currentPage++;
} else {
showNoMore();
}
} catch (error) {
showError();
} finally {
hideLoading();
}
}
function showLoading() {
document.querySelector('#loader').classList.remove('hidden');
}
function hideLoading() {
document.querySelector('#loader').classList.add('hidden');
}
虚拟滚动优化
对于大量数据,考虑实现虚拟滚动提高性能。
class VirtualScroll {
constructor(container, items, itemHeight) {
this.container = container;
this.items = items;
this.itemHeight = itemHeight;
this.visibleItems = Math.ceil(container.clientHeight / itemHeight);
this.startIndex = 0;
this.render();
container.addEventListener('scroll', () => this.handleScroll());
}
handleScroll() {
const scrollTop = this.container.scrollTop;
this.startIndex = Math.floor(scrollTop / this.itemHeight);
this.render();
}
render() {
const endIndex = Math.min(
this.startIndex + this.visibleItems,
this.items.length
);
const fragment = document.createDocumentFragment();
for (let i = this.startIndex; i < endIndex; i++) {
const item = document.createElement('div');
item.className = 'item';
item.style.height = `${this.itemHeight}px`;
item.textContent = this.items[i];
fragment.appendChild(item);
}
this.container.innerHTML = '';
this.container.appendChild(fragment);
this.container.style.height = `${this.items.length * this.itemHeight}px`;
}
}
注意事项
- 使用防抖或节流优化滚动事件处理
- 考虑添加加载状态指示器
- 实现错误处理机制
- 移动端需要特殊处理触摸事件
- 大量数据时考虑虚拟滚动技术
- API设计应考虑分页参数和返回格式





