萬盛學電腦網

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

jQuery 實現無限滾動/懶加載:IntersectionObserver 現代化重構指南

傳統 scroll 監聽方案(不推薦新專案)

// 經典但有缺陷:scroll 事件高頻觸發、需手動計算閾值、主執行緒阻塞
var loading = false;
$(window).scroll(function () {
  if (loading) return;
  var scrollTop = $(window).scrollTop();
  var winHeight = $(window).height();
  var docHeight = $(document).height();
  // 距離底部 250px 觸發
  if (scrollTop + winHeight >= docHeight - 250) {
    loading = true;
    $('#loading').show();
    $.get('load.php?start=' + $('#loaded_max').val(), function (html) {
      $('body').append(html);
      $('#loaded_max').val(parseInt($('#loaded_max').val()) + 50);
      $('#loading').hide();
      loading = false;
    });
  }
});

缺陷分析

  • scroll 事件高頻觸發 → 必須 throttle/debounce
  • 手動計算 scrollTop + clientHeight >= scrollHeight - threshold 易出錯
  • 佈局變動(圖片載入、字體加載)導致高度跳動,觸發誤判
  • 無法精準檢測「元素進入視口」

現代標準:IntersectionObserver API

瀏覽器原生、異步、高效能、無需監聽 scroll、自動處理佈局變動。

核心概念

  • Target:被觀察元素(如「載入更多」觸發器、每張圖片)
  • Root:視口容器(默認 viewport,可指定可捲動祖先)
  • Threshold:觸發比例陣列 [0, 0.25, 0.5, 0.75, 1]
  • RootMargin:擴展/縮小觀察區域(如 '200px 0px' 提前 200px 觸發)

無限滾動標準實現

<div id="list">
  <!-- 列表項 -->
</div>
<div id="sentinel" style="height:20px;"></div> <!-- 觀察哨兵 -->

<script>
var sentinel = document.getElementById('sentinel');
var page = 1;
var loading = false;

var observer = new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting && !loading) {
      loadNextPage();
    }
  });
}, {
  rootMargin: '200px 0px', // 提前 200px 觸發
  threshold: 0.1
});

observer.observe(sentinel);

function loadNextPage() {
  loading = true;
  sentinel.textContent = '載入中...';

  fetch('/api/items?page=' + page + '&size=20')
    .then(function (res) { return res.json(); })
    .then(function (data) {
      if (data.items.length === 0) {
        sentinel.textContent = '沒有更多了';
        observer.unobserve(sentinel);
        return;
      }
      renderItems(data.items);
      page++;
      loading = false;
      sentinel.textContent = '';
    })
    .catch(function (err) {
      console.error(err);
      sentinel.textContent = '載入失敗,點擊重試';
      loading = false;
      // 可添加點擊重試邏輯
    });
}

function renderItems(items) {
  var list = document.getElementById('list');
  var frag = document.createDocumentFragment();
  items.forEach(function (item) {
    var div = document.createElement('div');
    div.className = 'item';
    div.textContent = item.title;
    frag.appendChild(div);
  });
  list.appendChild(frag);
}
</script>

圖片懶加載:loading="lazy" + IntersectionObserver 降級

<img data-src="large.jpg" alt="..." class="lazy">

<script>
if ('loading' in HTMLImageElement.prototype) {
  // 原生支援
  document.querySelectorAll('img.lazy').forEach(function (img) {
    img.src = img.dataset.src;
    img.loading = 'lazy';
  });
} else {
  // 降級:IntersectionObserver
  var imgObserver = new IntersectionObserver(function (entries, obs) {
    entries.forEach(function (entry) {
      if (entry.isIntersecting) {
        var img = entry.target;
        img.src = img.dataset.src;
        img.onload = function () { img.classList.add('loaded'); };
        obs.unobserve(img);
      }
    });
  }, { rootMargin: '100px 0px' });

  document.querySelectorAll('img.lazy').forEach(function (img) {
    imgObserver.observe(img);
  });
}
</script>

jQuery 封裝版(兼容舊專案)

$.fn.infiniteScroll = function (options) {
  var opts = $.extend({
    url: '',
    pageParam: 'page',
    size: 20,
    sentinel: null, // 必傳:觀察元素
    render: function (items, $container) {}, // 必傳:渲染函式
    onError: function (err) {},
    rootMargin: '200px 0px'
  }, options);

  var $sentinel = $(opts.sentinel);
  var page = 1;
  var loading = false;

  if (!window.IntersectionObserver) {
    // 降級:scroll + throttle
    return this.each(function () { legacyScroll(this); });
  }

  var observer = new IntersectionObserver(function (entries) {
    entries.forEach(function (entry) {
      if (entry.isIntersecting && !loading) load();
    });
  }, { rootMargin: opts.rootMargin });

  observer.observe($sentinel[0]);

  function load() {
    loading = true;
    $sentinel.text('載入中...');
    var params = {}; params[opts.pageParam] = page;
    $.get(opts.url, params)
      .done(function (data) {
        if (!data.items.length) {
          $sentinel.text('無更多內容');
          observer.unobserve($sentinel[0]);
          return;
        }
        opts.render(data.items, $(this));
        page++;
        loading = false;
        $sentinel.text('');
      })
      .fail(function (err) { opts.onError(err); loading = false; $sentinel.text('失敗,點擊重試'); });
  }

  // 點擊哨兵重試
  $sentinel.on('click', function () { if (!loading) load(); });

  return this;
};

// 使用
$('#list').infiniteScroll({
  url: '/api/articles',
  sentinel: '#sentinel',
  render: function (items, $container) {
    var html = items.map(function (it) { return '<div class="item">' + it.title + '</div>'; }).join('');
    $container.append(html);
  }
});

效能對比

指標scroll + throttleIntersectionObserver
主執行緒佔用高(頻繁計算幾何)極低(瀏覽器底層優化)
準確度易受佈局抖動影響像素級精準
瀏覽器支援全支援Chrome 51+, Firefox 55+, Safari 12.1+, Edge 15+
Polyfill 體積無需~2KB (w3c/IntersectionObserver)

結語

**拋棄 scroll 監聽,擁抱 IntersectionObserver**。它是現代無限滾動、圖片懶加載、曝光埋點、粘性定位的標準解法。配合原生 loading="lazy"、content-visibility: auto,構建極致性能的長列表體驗。

copyright © 萬盛學電腦網 all rights reserved