萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 滾動到底部自動載入 (無限滾動) 核心判斷邏輯

核心判斷式

$(window).scroll(function() {
    // 滾動條滾到底部觸發
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
        // 執行載入更多邏輯
        loadMore();
    }
});

參數解析

  • $(window).scrollTop():文檔已向上捲動的像素 (視窗頂部到文檔頂部距離)。
  • $(window).height():瀏覽器視窗可視高度。
  • $(document).height():整個文檔總高度。
  • 公式:scrollTop + clientHeight >= scrollHeight - threshold
  • threshold (如 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 節流 });

效能優化關鍵

  1. 節流/防抖:scroll 事件高頻觸發,必須用 setTimeout、requestAnimationFrame 或 lodash.throttle 限制檢查頻率。
  2. 標記 loading 狀態:防止重複請求。
  3. DOM 回收:長列表移除頂端不見元素 (IntersectionObserver 或手動 remove()),防止記憶體暴增。
  4. 預載入:在距離底部 500px 時就觸發請求,資料回來前使用者已捲到位置。

現代替代:IntersectionObserver (零 scroll 事件)

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 方案。

copyright © 萬盛學電腦網 all rights reserved