js实现下拉加载
实现下拉加载的基本原理
监听滚动事件,判断是否滚动到页面底部。当滚动到底部时触发数据加载。核心逻辑包括计算滚动位置、判断触底条件和异步加载数据。
监听滚动事件
在JavaScript中,可以通过window.addEventListener监听scroll事件。确保在组件挂载时添加事件监听,并在卸载时移除以避免内存泄漏。

window.addEventListener('scroll', handleScroll);
判断滚动到底部
计算当前滚动位置与文档总高度的关系,判断是否到达底部。通常使用以下公式:
scrollTop + clientHeight >= scrollHeight - threshold
其中threshold是一个阈值,用于提前触发加载。

function handleScroll() {
const scrollTop = document.documentElement.scrollTop;
const clientHeight = document.documentElement.clientHeight;
const scrollHeight = document.documentElement.scrollHeight;
const threshold = 100; // 提前100px触发加载
if (scrollTop + clientHeight >= scrollHeight - threshold) {
loadMoreData();
}
}
加载数据
实现异步加载数据的函数,通常是一个API请求。确保在加载过程中禁用重复请求,并在加载完成后更新状态。
let isLoading = false;
async function loadMoreData() {
if (isLoading) return;
isLoading = true;
try {
const newData = await fetchData(); // 替换为实际API调用
appendDataToDOM(newData); // 更新DOM
} catch (error) {
console.error('加载失败:', error);
} finally {
isLoading = false;
}
}
优化性能
使用节流函数减少scroll事件的触发频率,避免性能问题。以下是一个简单的节流实现:
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
func.apply(this, args);
};
}
window.addEventListener('scroll', throttle(handleScroll, 200));
完整示例代码
let isLoading = false;
let currentPage = 1;
window.addEventListener('scroll', throttle(handleScroll, 200));
function handleScroll() {
const scrollTop = document.documentElement.scrollTop;
const clientHeight = document.documentElement.clientHeight;
const scrollHeight = document.documentElement.scrollHeight;
const threshold = 100;
if (scrollTop + clientHeight >= scrollHeight - threshold) {
loadMoreData();
}
}
async function loadMoreData() {
if (isLoading) return;
isLoading = true;
try {
const newData = await fetch(`/api/data?page=${currentPage}`);
const data = await newData.json();
appendDataToDOM(data);
currentPage++;
} catch (error) {
console.error('加载失败:', error);
} finally {
isLoading = false;
}
}
function appendDataToDOM(data) {
const container = document.getElementById('container');
data.forEach(item => {
const element = document.createElement('div');
element.textContent = item.content;
container.appendChild(element);
});
}
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
func.apply(this, args);
};
}
注意事项
- 确保在数据加载完成前禁用重复请求。
- 使用节流函数优化性能,避免频繁触发滚动事件。
- 在单页应用(SPA)中,组件卸载时需要移除事件监听。
- 考虑添加加载指示器,提升用户体验。






