無限滾動(Infinite Scroll)透過監聽滾動位置,在使用者接近底部時自動載入更多資料,提升體驗並減少首屏負載。本文從傳統 scroll 事件重構為 IntersectionObserver,並完善後端分頁協議、Loading 狀態、錯誤重試、虛擬滾動銜接。
$(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 觸發強制佈局。
<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>
// Request
POST /api/items
{ "page": 2, "pageSize": 20, "filter": { "category": "news" } }
// Response
{
"items": [ { "id": 21, "content": "..." }, ... ],
"page": 2,
"pageSize": 20,
"total": 156,
"hasMore": true
}
react-window、Clusterize.js,哨兵觀察器同樣適用。sessionStorage 緩存頁面 HTML,返回列表時秒現。<a href="?page=2"> 供爬蟲,或使用 SSR/SSG。aria-live="polite"、載入中 aria-busy="true"。// 若專案已大量使用 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 讓無限滾動從「效能殺手」變身「零成本體驗優化」,是現代前端必備技能。