DIV CSS 佈局教程網

jQuery 監聽捲軸事件:捲到底自動載入更多
編輯:關於JavaScript     

「捲到頁面底部自動載入下一批資料」是社群網站、商品列表的標準互動。實作的核心是監聽 scroll 事件,判斷是否已接近頁面底部,若是則觸發載入。

程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script type="text/javascript" src="jquery-1.6.2.js"></script>

<script type="text/javascript">
$(function(){
    var lazyheight = 0;

    // 取得資料
    function showload(){
        lazyheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
        if ($(document).height() - 100 <= lazyheight) {
            alert("xxx");        // 這裡換成你的載入邏輯
        }
    }

    // 綁定事件
    $(window).bind("scroll", function(){
        showload();
    });
});
</script>
</head>
<body>
<img src="82938048_46374805.jpg"/>
<img src="82938048_46374805.jpg"/>
<img src="82938048_46374805.jpg"/>
</body>
</html>

判斷式解析

$(window).height() 是視窗高度,$(window).scrollTop() 是已捲動距離,兩者相加就是視窗底緣在文件中的 Y 座標。

$(document).height() - 100 <= lazyheight 的意思是:文件總高度減去 100px 之後,若還小於等於視窗底緣位置,代表距離底部已經不遠(剩 100px 以內)。那個 100 是提前觸發的緩衝——等使用者真的捲到底才載入,他會看到一段空白等待;提前 100px 觸發,新內容往往在他抵達前就已經就位。

實務上必須補強的地方

1. 重複觸發的問題(最嚴重)。scroll 事件在捲動期間會連續觸發幾十次,每次都可能通過判斷條件,導致同一批資料被請求好幾次。必須加上「正在載入」的旗標:

var loading = false;

function showload(){
    if (loading) return;                       // 已在載入,跳過
    var lazyheight = $(window).height() + $(window).scrollTop();
    if ($(document).height() - 100 <= lazyheight){
        loading = true;
        $.get('/api/items?page=' + (++page), function(res){
            $('#list').append(res.html);
            loading = false;
            if (!res.hasMore) $(window).unbind('scroll');   // 沒有更多就解開
        }).fail(function(){
            loading = false;                    // 失敗也要解鎖
        });
    }
}

2. 捲動事件頻繁。scroll 的觸發頻率極高,每次都執行 DOM 查詢與計算會造成卡頓。應該加上節流(throttle):

function throttle(fn, wait){
    var last = 0;
    return function(){
        var now = Date.now();
        if (now - last >= wait){ last = now; fn.apply(this, arguments); }
    };
}
$(window).on('scroll', throttle(showload, 200));

3. 頁面太短時永遠觸發不了。若初始內容少於一屏,根本不會出現捲軸,scroll 事件永遠不觸發。所以頁面載入時應該先主動呼叫一次 showload()(原範例把這行註解掉了)。

4. 沒有載入指示。使用者不知道正在載入還是卡住了。應該顯示 loading 動畫,並在失敗時提供「重試」按鈕。

用原生 JavaScript 重寫

var page = 0, loading = false, hasMore = true;

function maybeLoad(){
    if (loading || !hasMore) return;
    var bottom = window.innerHeight + window.pageYOffset;
    if (document.documentElement.scrollHeight - bottom > 150) return;

    loading = true;
    showLoading();

    fetch('/api/items?page=' + (++page))
        .then(function(r){ if (!r.ok) throw new Error('載入失敗'); return r.json(); })
        .then(function(res){
            appendItems(res.items);
            hasMore = res.hasMore;
            if (!hasMore) showEndMessage();
        })
        .catch(function(e){ page--; showError(e.message); })
        .finally(function(){ loading = false; hideLoading(); });
}

window.addEventListener('scroll', throttle(maybeLoad, 200));
window.addEventListener('resize', throttle(maybeLoad, 200));
maybeLoad();          // 首次執行,處理內容不足一屏的情況

更好的方案:Intersection Observer

與其自行計算座標,不如放一個「哨兵元素」在列表底部,讓瀏覽器告訴你它何時進入視窗:

var sentinel = document.getElementById('sentinel');

var observer = new IntersectionObserver(function(entries){
    if (entries[0].isIntersecting && hasMore && !loading){
        loadMore();
    }
}, { rootMargin: '200px' });        // 提前 200px 觸發

observer.observe(sentinel);

這個做法不必監聽 scroll、不必算座標、效能由瀏覽器最佳化,程式碼也短得多,是目前的建議寫法。

體驗上的建議

  • 無限捲動並非萬靈丹。若使用者需要「回到底部」或「抵達某個位置」,無限捲動會讓這變得不可能。可考慮混合方案:自動載入前幾頁,之後改成「載入更多」按鈕。
  • 記得處理 URL 狀態。使用者重新整理後應該回到原本的位置,這需要把 page 寫進 query string 或 hash。
  • 新內容插入時若會改變捲動位置,容易造成跳動。必要時在插入前記錄 scrollY,插入後還原。
  • 提供 footer 是必要的——無限捲動會讓頁尾永遠到不了,連結與版權資訊會變成迷霧。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved