前端開發中頻繁需要刷新當前頁、父頁、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);
假設頂層頁 `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 通信。
<script>
function autoRefresh() {
window.location.reload();
}
setInterval(autoRefresh, 60000); // 每 60 秒刷新一次
</script>
<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>
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、移動端優先應用 |
fetch/AJAX 局部更新,避免整頁刷新體驗差。location.reload() 而非 href=href(避免歷史棧膨脹)。message 事件,子頁 parent.postMessage('reload', '*')。visibilitychange 守護,隱藏標籤頁停止輪詢,省電省帶寬。ETag/Last-Modified,304 Not Modified 節省流量。