561 字
3 分鐘

按上一頁看到舊資料?用 pageshow 判斷 bfcache 還原

本文目錄

從編輯頁回到清單,剛改的標題還顯示舊值,重新整理才正確。先在清單頁監聽 window 的 pageshow。若 event.persisted 是 true,瀏覽器從 back/forward cache(bfcache)恢復原本的文件與 JavaScript 狀態。可在這時重新讀取會變動的資料,保留原本的捲動位置與其他介面狀態。WHATWG HTML:PageTransitionEvent · Chrome:Back/forward cache

用兩頁驗證:文件沒重建,資料仍可更新#

將下面兩個檔案放在同個資料夾,在該資料夾執行 python3 -m http.server 8000,用瀏覽器開啟 http://localhost:8000/list.html。範例以 sessionStorage 模擬儲存資料,兩頁要使用相同的 host 和 port。

list.html
<!doctype html>
<html lang="zh-Hant">
<meta charset="utf-8">
<title>清單</title>
<p id="title"></p>
<a href="./edit.html">到編輯頁</a>
<pre id="events"></pre>
<script>
const title = document.querySelector('#title');
const events = document.querySelector('#events');
const readTitle = () => {
title.textContent = sessionStorage.getItem('demoTitle') ?? '舊標題';
};
readTitle();
window.addEventListener('pageshow', (event) => {
events.textContent += 'pageshow persisted=' + event.persisted + '\n';
if (event.persisted) readTitle();
});
</script>
</html>
edit.html
<!doctype html>
<html lang="zh-Hant">
<meta charset="utf-8">
<title>編輯</title>
<button type="button" id="save">儲存並返回</button>
<script>
document.querySelector('#save').addEventListener('click', () => {
sessionStorage.setItem('demoTitle', '新標題');
history.back();
});
</script>
</html>

第一次開啟會記下 persisted=false。按「到編輯頁」再按「儲存並返回」。若同一個清單還保留第一行事件記錄,後面多出 persisted=true,且標題變新,就同時驗證了還原與局部更新。把清單的 if (event.persisted) readTitle() 暫時註解,清掉 sessionStorage 的 demoTitle 後再走一次,便能看見還原舊畫面的情況。若後退時只有一筆 persisted=false,屬於重新載入,清單在初始化就會讀到新值。Chrome 可用 Application → Back/forward cache 查看目標頁面是否能還原。Chrome DevTools 操作說明

把更新掛在正確的生命週期#

  • 跨頁導覽可在一般初始化載入資料,從 bfcache 回來時再重取變動區塊,例如清單、購物車數量或登入狀態。若改用 API,另外驗證請求的快取政策與回傳值,並避免慢回應覆蓋新狀態。JavaScript fetch 競態排查
  • SPA 同文件切換交給路由的 loader、進入頁面時的資料重驗或應用本身的快取失效機制。persisted 只能告訴你文件是否被還原,無法涵蓋同文件的上一頁。

參考資料:

WHATWG HTML:PageTransitionEvent

Chrome:Back/forward cache

Chrome DevTools:Test back/forward cache

按上一頁看到舊資料?用 pageshow 判斷 bfcache 還原
https://laplusda.com/posts/javascript-pageshow-bfcache/
作者
Zero
發佈於
2026-11-23
許可協議
CC BY-NC-SA 4.0