jquery滚动加载
jQuery 滚动加载实现方法
滚动加载(Infinite Scroll)是一种常见的前端技术,通过监听滚动事件动态加载更多内容。以下是几种实现方式:
基础滚动监听实现
监听窗口滚动事件,判断是否滚动到底部触发加载:
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
loadMoreContent();
}
});
function loadMoreContent() {
// 防止重复加载
if (isLoading) return;
isLoading = true;
$.ajax({
url: 'your-api-endpoint',
data: { page: currentPage },
success: function(data) {
$('#container').append(data);
currentPage++;
},
complete: function() {
isLoading = false;
}
});
}
使用Intersection Observer API
现代浏览器推荐使用更高效的Intersection Observer:
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreContent();
}
}, { threshold: 1.0 });
observer.observe(document.querySelector('#load-more-trigger'));
// HTML中需要有一个触发元素
<div id="load-more-trigger"></div>
使用现成插件
jQuery插件简化实现:
- 引入jquery.infinitescroll.js
- 基础配置:
$('#container').infinitescroll({ navSelector: ".pagination", nextSelector: ".pagination a.next", itemSelector: ".item", loading: { msgText: "加载中...", finishedMsg: "没有更多内容了" } });
性能优化建议
添加防抖机制避免频繁触发:
var scrollTimeout;
$(window).scroll(function() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(function() {
// 滚动检测逻辑
}, 250);
});
预加载机制可以提前半页开始加载:
const preloadThreshold = 0.5; // 提前50%高度加载
if ($(window).scrollTop() + $(window).height() >= $(document).height() * preloadThreshold)
移动端注意事项
移动端需要额外处理touch事件:
$(document).on('touchmove', function(e) {
// 移动端滚动处理
});
这些方法可以根据实际需求选择或组合使用,核心原理都是监听滚动位置变化并触发内容加载。







