萬盛學電腦網

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

jQuery + AJAX 無限滾動加載:IntersectionObserver 現代化重構與後端分頁配合

無限滾動(Infinite Scroll)透過監聽滾動位置,在使用者接近底部時自動載入更多資料,提升體驗並減少首屏負載。本文從傳統 scroll 事件重構為 IntersectionObserver,並完善後端分頁協議、Loading 狀態、錯誤重試、虛擬滾動銜接。

傳統 scroll 事件寫法(有效能隱憂)

$(document).ready(function() {
  let loading = false;
  $('#mainDiv').scroll(function() {
    if (loading) return;
    const scrollTop = $(this).scrollTop();
    const scrollHeight = $('#wrapperDiv').height();
    const clientHeight = $(this).height();
    if (scrollTop + clientHeight >= scrollHeight - 100) { // 提前 100px 觸發
      loading = true;
      $.ajax({
        type: 'POST',
        url: 'LoadOnScroll.aspx/GetDataFromServer',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: '{}',
        success: function(msg) {
          $('#wrapperDiv').append(msg.d);
          loading = false;
        },
        error: function(xhr) {
          alert('載入失敗: ' + xhr.responseText);
          loading = false;
        }
      });
    }
  });
});

缺點:scroll 高頻觸發主執行緒負擔大、需手動計算幾何屬性、scrollTop 觸發強制佈局。

現代重構:IntersectionObserver(零主執行緒負擔)

<div id="scrollContainer" style="height: 600px; overflow-y: auto;">
  <div id="dataWrapper"></div>
  <div id="sentinel" style="height: 20px;"></div> <!-- 哨兵元素 -->
</div>

<script>
const sentinel = document.getElementById('sentinel');
const wrapper = document.getElementById('dataWrapper');
let loading = false;
let page = 1;
const pageSize = 20;

const observer = new IntersectionObserver(async (entries) => {
  if (loading) return;
  const entry = entries[0];
  if (!entry.isIntersecting) return; // 哨兵未進入視口

  loading = true;
  sentinel.textContent = '載入中...';

  try {
    const res = await fetch('/api/items', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ page, pageSize })
    });
    const { items, hasMore } = await res.json();
    
    if (items.length) {
      // 使用 DocumentFragment 批次插入,減少重排
      const fragment = document.createDocumentFragment();
      items.forEach(item => {
        const div = document.createElement('div');
        div.className = 'item';
        div.textContent = `${item.id}: ${item.content}`;
        fragment.appendChild(div);
      });
      wrapper.appendChild(fragment);
      page++;
    }
    
    if (!hasMore) {
      sentinel.textContent = '沒有更多了';
      observer.disconnect(); // 停止觀察
    } else {
      sentinel.textContent = '';
    }
  } catch (err) {
    sentinel.textContent = '載入失敗,點擊重試';
    sentinel.onclick = () => { sentinel.onclick = null; loading = false; };
  } finally {
    loading = false;
  }
}, {
  root: document.getElementById('scrollContainer'), // 滾動容器
  rootMargin: '100px 0px', // 提前 100px 觸發
  threshold: 0.1
});

observer.observe(sentinel);
</script>

後端分頁協議設計(RESTful)

// Request
POST /api/items
{ "page": 2, "pageSize": 20, "filter": { "category": "news" } }

// Response
{
  "items": [ { "id": 21, "content": "..." }, ... ],
  "page": 2,
  "pageSize": 20,
  "total": 156,
  "hasMore": true
}

進階優化技巧

  • 虛擬滾動結合:資料量極大時,僅渲染可視區 DOM,配合 react-window、Clusterize.js,哨兵觀察器同樣適用。
  • 防抖/節流不再需要:IntersectionObserver 回呼在瀏覽器空閒期執行,天然非阻塞。
  • 快取已載入頁面:sessionStorage 緩存頁面 HTML,返回列表時秒現。
  • SEO 友善:提供分頁連結 <a href="?page=2"> 供爬蟲,或使用 SSR/SSG。
  • 無障礙:哨兵加 aria-live="polite"、載入中 aria-busy="true"。

jQuery 專案漸進式升級

// 若專案已大量使用 jQuery,可混用
const $sentinel = $('#sentinel');
const observer = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting && !loading) loadMore();
}, { root: $('#scrollContainer')[0], rootMargin: '100px' });
observer.observe($sentinel[0]);

function loadMore() {
  loading = true;
  $.ajax({ /* ... */ }).always(() => loading = false);
}

IntersectionObserver 讓無限滾動從「效能殺手」變身「零成本體驗優化」,是現代前端必備技能。

copyright © 萬盛學電腦網 all rights reserved