// 經典但有缺陷: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/debouncescrollTop + clientHeight >= scrollHeight - threshold 易出錯瀏覽器原生、異步、高效能、無需監聽 scroll、自動處理佈局變動。
[0, 0.25, 0.5, 0.75, 1]'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>
$.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 + throttle | IntersectionObserver |
|---|---|---|
| 主執行緒佔用 | 高(頻繁計算幾何) | 極低(瀏覽器底層優化) |
| 準確度 | 易受佈局抖動影響 | 像素級精準 |
| 瀏覽器支援 | 全支援 | Chrome 51+, Firefox 55+, Safari 12.1+, Edge 15+ |
| Polyfill 體積 | 無需 | ~2KB (w3c/IntersectionObserver) |
**拋棄 scroll 監聽,擁抱 IntersectionObserver**。它是現代無限滾動、圖片懶加載、曝光埋點、粘性定位的標準解法。配合原生 loading="lazy"、content-visibility: auto,構建極致性能的長列表體驗。