萬盛學電腦網

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

基於 jQuery 實現滾動到底部自動加載更多(無限滾動/瀑布流核心邏輯)

效果描述

當用戶滾動頁面至底部附近時,自動觸發 AJAX 請求獲取更多數據並追加到頁面,類似微博、新浪新聞評論列表的「無限滾動」體驗。核心邏輯:監聽 `scroll` 事件,對比視口高度+滾動高度與文檔總高度,達到臨界值發起請求,並用鎖機制防止重複請求。

核心代碼實現

var stop = true; // 請求鎖,防止並發

$(window).scroll(function() {
    // 視口高度 + 滾動距離
    var totalHeight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());

    // 到達文檔底部(或距底部極近)
    if ($(document).height() <= totalHeight) {
        if (stop === true) {
            stop = false; // 加鎖

            $.post("ajax.php", { start: 1, n: 50 }, function(txt) {
                // 將返回內容插入到加載提示元素之前
                $("#Loading").before(txt);
                stop = true; // 解鎖
            }, "text");
        }
    }
});

HTML 結構

<div id="Loading">Loading...</div>

新內容通過 `.before(txt)` 插入到 `#Loading` 之前,使加載提示始終保持在最底部。

關鍵點深度解析

1. 滾動位置計算

  • `$(window).height()`:可視區高度。
  • `$(window).scrollTop()`:已滾動距離。
  • `$(document).height()`:整個文檔高度(含未滾動顯示部分)。
  • 當 `視口高度 + 滾動距離 >= 文檔高度` 時,視為到達底部。

2. 請求鎖 (`stop` 變量)

AJAX 請求是異步的,若無鎖機制,在請求未返回期間用戶繼續滾動會多次觸發 `scroll` 事件,導致發起多個並發請求,造成數據重複、服務器壓力增大。`stop` 變量確保同一時間僅有一個請求在進行。

3. 性能優化建議

  • 節流/防抖:`scroll` 事件高頻觸發,建議使用 `setTimeout` 或 `requestAnimationFrame` 節流,或使用 Lodash `_.throttle`。
  • 提前觸發閾值:不要等到完全到底部,而是距底部 100~200px 時預加載,提升體驗:
    if ($(document).height() - totalHeight < 200) { ... }
  • 使用 Intersection Observer API(現代瀏覽器):觀察一個放在列表末尾的哨兵元素是否進入視口,完全避免 `scroll` 事件監聽,性能更優。
  • 虛擬列表:數據量極大時,配合虛擬滾動技術(如 react-window、vue-virtual-scroller)只渲染可視區 DOM。

完整優化版示例(含節流與提前加載)

var loading = false;
var buffer = 200; // 提前 200px 觸發

$(window).on('scroll', _.throttle(function() {
    if (loading) return;

    var scrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var docHeight = $(document).height();

    if (docHeight - (scrollTop + windowHeight) < buffer) {
        loading = true;
        $("#Loading").show();

        $.getJSON("/api/more", { page: nextPage }, function(data) {
            if (data.items.length) {
                $("#Loading").before(renderItems(data.items));
                nextPage++;
            } else {
                $("#Loading").text("已無更多內容").delay(2000).fadeOut();
                $(window).off('scroll'); // 移除監聽
            }
            loading = false;
        });
    }
}, 200))); // 200ms 節流
copyright © 萬盛學電腦網 all rights reserved