萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

JavaScript 刷新页面/框架的 7 种方法与定时自动刷新实现

JavaScript 刷新页面/框架的 7 种方法与定时自动刷新实现

前端開發中頻繁需要刷新當前頁、父頁、iframe 子頁或跨域框架。本文整理 7 種原生 JS 刷新寫法、框架場景下的跨框架刷新技巧、定時自動刷新實現,並說明同源策略限制與現代替代方案。

一、同源同窗口刷新(最常用)

// 1. 標準重載(保留 POST 數據會提示確認)
window.location.reload();

// 2. 強制從服務器獲取(繞過緩存)
window.location.reload(true);  // 非標準,僅 IE/Edge 支援

// 3. 替換當前歷史記錄(無法後退)
window.location.replace(window.location.href);

// 4. 直接賦值 href(會新增歷史記錄)
window.location.href = window.location.href;

// 5. 歷史記錄去重刷新
window.history.go(0);

二、跨框架/iframe 刷新(同源策略前提)

假設頂層頁 `top.html` 嵌入 `bottom.html` (name="bottom" / index=1),以下 7 種寫法等效:

// 在 top.html 中按鈕 onclick 處理器
// 1. 索引訪問
window.parent.frames[1].location.reload();

// 2. name 訪問(推薦,語義清晰)
window.parent.frames['bottom'].location.reload();
window.parent.frames.bottom.location.reload();

// 3. item() 方法
window.parent.frames.item(1).location.reload();
window.parent.frames.item('bottom').location.reload();

// 4. 直接屬性訪問(需 iframe name=id 且無同名全局變量)
window.parent.bottom.location.reload();
window.parent['bottom'].location.reload();

⚠️ 同源策略限制:跨域 iframe 無法訪問 `contentWindow.location`,會拋 SecurityError。跨域刷新需用 postMessage 通信。

三、定時自動刷新實現

1. 簡單定時器(頁面可見時刷新)

<script>
function autoRefresh() {
    window.location.reload();
}
setInterval(autoRefresh, 60000); // 每 60 秒刷新一次
</script>

2. 可見性 API 節省資源(推薦)

<script>
let refreshTimer;
function startAutoRefresh(intervalMs = 60000) {
    if (document.hidden) return; // 頁面隱藏不啟動
    refreshTimer = setInterval(() => {
        if (!document.hidden) window.location.reload();
    }, intervalMs);
}
document.addEventListener('visibilitychange', () => {
    if (document.hidden) clearInterval(refreshTimer);
    else startAutoRefresh();
});
startAutoRefresh();
</script>

3. 無感知局部刷新(AJAX/Fetch + DOM 更新)

async function refreshPartial() {
    try {
        const res = await fetch('/api/latest-data');
        const data = await res.json();
        // 更新特定 DOM 節點,不整頁刷新
        document.getElementById('counter').textContent = data.count;
    } catch (e) { console.error('刷新失敗', e); }
}
setInterval(refreshPartial, 30000);

四、現代替代方案對比

方案優點缺點適用場景
location.reload()簡單、保證狀態重置閃屏、丟失滾動位置、表單數據低頻、簡單頁面
AJAX 局部更新無閃屏、保持狀態、體驗好需後端配合 API、狀態同步複雜儀表盤、即時數據、長連接頁面
WebSocket / SSE服務端推送、零延遲、無輪詢連接管理複雜、需兼容處理高實時性:聊天、股票、協作編輯
Service Worker + Background Sync離線可用、後台同步瀏覽器支持度、調試難PWA、移動端優先應用

五、最佳實踐清單

  1. 優先用 fetch/AJAX 局部更新,避免整頁刷新體驗差。
  2. 必須整頁刷新時,用 location.reload() 而非 href=href(避免歷史棧膨脹)。
  3. 跨域 iframe 刷新:父頁監聽 message 事件,子頁 parent.postMessage('reload', '*')。
  4. 定時刷新必加 visibilitychange 守護,隱藏標籤頁停止輪詢,省電省帶寬。
  5. 生產環境給刷新接口加 ETag/Last-Modified,304 Not Modified 節省流量。
copyright © 萬盛學電腦網 all rights reserved