JS刷新页面8种方法全解析

使用 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)中直接刷新可能导致状态丢失,需结合框架特性处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值