萬盛學電腦網

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

jQuery 實現無限滾動加載(瀑布流/列表分頁)完整教程

核心邏輯

監聽 window.scroll 事件,當滾動條距離頁面底部小於閾值時,觸發 AJAX 請求追加數據。

關鍵判斷公式

// 視口高度 + 滾動距離 >= 文檔高度 - 閾值
$(window).height() + $(window).scrollTop() >= $(document).height() - threshold

完整可用代碼

$(function() {
    var $content = $("#content");
    var page = 1;
    var pageSize = 10;
    var loading = false;
    var threshold = 50; // 提前 50px 觸發

    function loadMore() {
        if (loading) return;
        loading = true;
        $content.append("
加載中...
"); $.getJSON("/api/items", { page: page, size: pageSize }) .done(function(data) { $(".loading").remove(); if (data.length === 0) { $content.append("
已無更多數據
"); $(window).off("scroll", scrollHandler); // 解除綁定 return; } // 渲染數據 var html = data.map(function(item) { return "
" + item.title + "
"; }).join(""); $content.append(html); page++; loading = false; }) .fail(function() { $(".loading").remove(); $content.append("
加載失敗,請重試
"); loading = false; }); } function scrollHandler() { var scrollTop = $(window).scrollTop(); var docHeight = $(document).height(); var winHeight = $(window).height(); if (winHeight + scrollTop >= docHeight - threshold) { loadMore(); } } $(window).on("scroll", scrollHandler); // 初始加載第一頁 loadMore(); });

性能優化要點

  1. 節流/防抖:使用 _.throttle 或 requestAnimationFrame 限制 scroll 事件頻率。
  2. 虛擬列表:大數據量時移除可視區外 DOM,僅保留可視區 + 緩衝區節點。
  3. IntersectionObserver API:現代瀏覽器原生支持,無需監聽 scroll,性能極佳。
    var observer = new IntersectionObserver(function(entries) {
        if (entries[0].isIntersecting) loadMore();
    }, { rootMargin: '100px' });
    observer.observe(document.querySelector('.load-trigger'));
  4. 防止重複請求:loading 標誌位 + 移除觸發元素觀察。

常見坑點

  • 固定高度容器導致 $(document).height() 不準,應監聽容器 scroll 而非 window。
  • 圖片未加載導致高度變化,觸發誤判 → 圖片 onload 後重新計算或預留高度。
  • 移動端地址欄隱藏/顯示改變視口高度,需監聽 resize 重算。
copyright © 萬盛學電腦網 all rights reserved