使用 location.reload()
location.reload() 是刷新当前页面的标准方法。默认情况下会从浏览器缓存加载页面,若需强制从服务器重新加载,可传入参数 true。
location.reload(); // 可能从缓存加载
location.reload(true); // 强制从服务器加载
使用 location.href
通过重新赋值 location.href 或直接调用 location.assign() 实现页面刷新。这种方式会保留浏览历史记录。
location.href = location.href;
// 或
location.assign(location.href);
使用 location.replace()
location.replace() 会替换当前页面,但不会在浏览器历史记录中生成新条目,适合某些需要静默刷新的场景。
location.replace(location.href);
使用 history.go()
通过 history.go() 控制浏览器历史记录跳转。传入 0 表示刷新当前页面。
history.go(0);
使用 meta 标签
在 HTML 的 <head> 中添加 meta 标签可自动刷新页面,通过 content 指定刷新时间(秒)。
<meta http-equiv="refresh" content="0">
使用表单提交
通过 JavaScript 动态创建并提交一个空表单,模拟页面刷新行为。
const form = document.createElement('form');
form.method = 'GET';
form.action = window.location.href;
document.body.appendChild(form);
form.submit();
使用 fetch 和替换内容
通过 fetch 获取当前页面内容并替换当前文档,适用于需要精细控制刷新逻辑的场景。
fetch(window.location.href, { cache: 'no-cache' })
.then(response => response.text())
.then(html => document.open().write(html));
使用 Service Worker
在 Service Worker 中拦截请求并动态控制页面刷新逻辑,适合 PWA 应用。
// Service Worker 代码
self.addEventListener('fetch', event => {
event.respondWith(fetch(event.request));
});
使用框架特性
在 React/Vue/Angular 等框架中,可通过路由或状态管理触发页面刷新:
React 示例
// 使用 useNavigate (React Router v6)
const navigate = useNavigate();
navigate(0);
// 或直接操作 window
window.location.reload();
Vue 示例
// 使用 router
this.$router.go(0);
注意事项
- 缓存问题:强制刷新可能跳过缓存,但会增加服务器负载。
- 用户体验:频繁刷新可能导致页面闪烁,建议配合加载动画使用。
- 框架兼容性:在单页应用(SPA)中直接刷新可能导致状态丢失,需结合框架特性处理。



3230

被折叠的 条评论
为什么被折叠?



