js实现页面自动刷新
使用 location.reload() 方法
通过调用 location.reload() 可以实现页面刷新。可以结合 setInterval 定时触发刷新。
// 每5秒刷新一次页面
setInterval(() => {
location.reload();
}, 5000);
使用 meta 标签自动刷新
在 HTML 的 <head> 中添加 meta 标签,通过 http-equiv="refresh" 实现自动刷新。
<meta http-equiv="refresh" content="5">
content 值为刷新间隔时间(秒)。
使用 fetch 检测数据变化后刷新
通过定时请求接口或检查数据变化,再决定是否刷新页面。
setInterval(async () => {
const response = await fetch('/api/check-update');
const data = await response.json();
if (data.updated) {
location.reload();
}
}, 3000);
监听特定事件触发刷新
例如监听 storage 事件,当本地存储数据变化时刷新页面。

window.addEventListener('storage', (event) => {
if (event.key === 'reload-flag') {
location.reload();
}
});
注意事项
- 自动刷新可能影响用户体验,建议仅在必要时使用。
- 频繁刷新会增加服务器负载,需合理设置间隔时间。
- 单页应用(SPA)推荐使用局部更新而非整页刷新。






