$(window).scroll(function() {
// 滾動條滾到底部觸發
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
// 執行載入更多邏輯
loadMore();
}
});
$(window).scrollTop():文檔已向上捲動的像素 (視窗頂部到文檔頂部距離)。$(window).height():瀏覽器視窗可視高度。$(document).height():整個文檔總高度。scrollTop + clientHeight >= scrollHeight - thresholdthreshold (如 10px) 提前觸發,避免使用者捲到底才開始載入,體驗更流暢。var page = 1;
var loading = false;
var hasMore = true;
function loadMore() {
if (loading || !hasMore) return;
loading = true;
$('#loading').show(); // 顯示載入中指示器
$.ajax({
url: '/api/articles',
data: { page: page, size: 10 },
dataType: 'json',
success: function(data) {
if (data.length === 0) {
hasMore = false;
$('#loading').hide().after('已無更多內容
');
return;
}
// 渲染資料
var html = data.map(item => `
<article>
<h3>${escapeHtml(item.title)}</h3>
<p>${escapeHtml(item.summary)}</p>
</article>
`).join('');
$('#content').append(html);
page++;
},
error: function() {
alert('載入失敗,請稍後再試');
},
complete: function() {
loading = false;
$('#loading').hide();
}
});
}
// 簡易 HTML 轉義防 XSS
function escapeHtml(text) {
var div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 綁定滾動事件 (節流優化)
var scrollTimer;
$(window).scroll(function() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
loadMore();
}
}, 100); // 100ms 節流
});
scroll 事件高頻觸發,必須用 setTimeout、requestAnimationFrame 或 lodash.throttle 限制檢查頻率。IntersectionObserver 或手動 remove()),防止記憶體暴增。var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting && !loading && hasMore) {
loadMore();
}
});
}, { rootMargin: '200px' }); // 提前 200px 觸發
// 觀察一個置底的 sentinel 元素
observer.observe(document.getElementById('sentinel'));
// HTML 末尾加入
// <div id="sentinel" style="height:1px"></div>
優點:無 scroll 監聽器、主執行緒零負擔、精準觸發。支援所有現代瀏覽器 (IE 需 Polyfill)。
判斷滾動到底部公式:scrollTop + clientHeight >= scrollHeight - threshold。生產環境務必加上節流、loading 鎖、DOM 回收、錯誤重試。新專案強烈建議改用 IntersectionObserver 方案。