JavaScript 硬刷新当前页面
如何通过 JavaScript 强制 Web 浏览器对页面进行硬刷新?
硬刷新意味着获取页面的全新副本并刷新所有外部资源(图像、JavaScript、CSS 等)。
How can I force the web browser to do a hard refresh of the page via JavaScript?
Hard refresh means getting a fresh copy of the page AND refresh all the external resources (images, JavaScript, CSS, etc.).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
上面接受的答案除了在当今大多数新版本的网络浏览器上正常重新加载之外不再执行任何操作。我在最近更新的 Chrome 上尝试了所有这些,包括
location.reload(true)
、location.href = location.href
和。他们都没有工作。
我的解决方案是使用服务器端功能将非重复查询字符串附加到所有包含的源文件引用,如下例所示。
所以你还需要动态控制它何时保留上一个文件以及何时更新。唯一的问题是,当插件通过脚本执行文件包含时,您无法控制修改它。不用担心源文件泛滥。当旧文件取消链接时,它将被自动垃圾收集。
Accepted answer above no longer does anything except just a normal reloading on mostly new version of web browsers today. I've tried on my recently updated Chrome all those, including
location.reload(true)
,location.href = location.href
, and<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
. None of them worked.My solution is by using server-side capability to append non-repeating query string to all included source files reference as like below example.
<script src="script.js?t=<?=time();?>"></script>
So you also need to control it dynamically when to keep previous file and when to update it. The only issue is when files inclusion is performed via script by plugins you have no control to modify it. Don't worry about source files flooding. When older file is unlinked it will be automatically garbage collected.
这是 2022 年的更新,有 2 种方法,考虑到 SPA 的 url 中带有
#
:方法 1:
正如其他答案中提到的,一种解决方案是将随机参数放入查询字符串。在 javascript 中,可以通过以下方式实现:
不好的部分是它会更改当前的 url,有时,在干净的 url 中,对于用户来说,它可能看起来有点难看。
方法 2:
借鉴 https://splunktool.com/force-a-reload-of-page-in-chrome-using-javascript-no-cache,过程可能是先获取没有缓存的url然后重新加载页面:
甚至可以与方法 1 结合使用,但我认为使用 headers 应该足够了:
This is a 2022 update with 2 methods, considering SPA's with
#
in url:METHOD 1:
As mentioned in other answers one solution would be to put a random parameter to query string. In javascript it could be achieved with this:
The bad part is that it changes the current url and sometimes, in clean url's, it could seem little bit ugly for users.
METHOD 2:
Taking the idea from https://splunktool.com/force-a-reload-of-page-in-chrome-using-javascript-no-cache, the process could be to get the url without cache first and then reload the page:
Could be even combined with method 1, but I think that with headers should be enought:
使用搜索参数更改当前 URL 将导致浏览器将相同的参数传递到服务器,换句话说,强制刷新。
(不过,如果您对 Service Worker 使用拦截,则不能保证。)
如果您想支持较旧的浏览器:
也就是说,强制刷新所有 CSS 和 JS 有点费力。您可能需要执行相同的过程,为
中的所有
src
属性和< 中的
。也就是说,它不会卸载当前的 JS,但对于 CSS 来说可以正常工作。href
添加 searchParam ;链接>我不会费心使用 JS 示例,因为它可能只会引起问题。
您可以通过在编译 HTML 时在 JS 和 CSS 链接中添加时间戳作为搜索参数来避免这种麻烦。
Changing the current URL with a search parameter will cause browsers to pass that same parameter to the server, which in other words, forces a refresh.
(No guarantees if you use intercept with a Service Worker though.)
If you want support older browsers:
That said, forcing all your CSS and JS to refresh is a bit more laborious. You would want to do the same process of adding a searchParam for all the
src
attributes in<script>
andhref
in<link>
. That said it won't unload the current JS, but would work fine for CSS.I won't bother with a JS sample since it'll likely just cause problems.
You can save this hassle by adding a timestamp as a search param in your JS and CSS links when compiling the HTML.
更新刷新所有外部资源(图像、JavaScript、CSS等)
将其放入名为
HardRefresh.js
的文件中:此代码执行以下操作对每个访问者进行完全控制的强制硬刷新,以便任何更新都会显示而不会出现兑现问题。
重复的 DOM 渲染不是性能问题,因为第一次渲染来自缓存,并且它在从服务器重新加载页面的
中停止渲染。当它运行刷新的页面时,它也会刷新页面中的网址。
最后刷新时间
x
存储在localStorage中。与当前时间t
进行比较,在10秒内刷新。假设从服务器加载的时间不超过 10 秒,我们设法停止页面刷新循环,因此不要让它少于 10 秒。对于页面的访问者来说,
x != t
自从很久以前或第一次访问以来就为 true;将从服务器获取页面。然后 diff 小于 10 秒且x == t
,这将使else
部分将查询字符串添加到href
和src< /code> 有源需要刷新。
可以通过按钮或其他有条件的方式调用refresh()函数。完全控制是通过在代码中细化 URL 的排除和包含来管理的。
UPDATED to refresh all the external resources (images, JavaScript, CSS, etc.)
Put this in file named
HardRefresh.js
:This code do a fully controled forced hard refresh for every visitor, so that any update will show up without a cashing problem.
Duplicated DOM rendering is not a performance issue, because the first render is from cache and it stops rendering in
<script src="js/HardRefresh.js">
where it reload a page from server. When it run a refreshed page it also refresh urls in page.The last refresh time
x
is stored in localStorage. It is compared with the current timet
to refresh within 10 seconds. Assuming a load from server not take more than 10 sec we manage to stop a page refresh loop, so do not have it less than 10s.For a visitor of page the
x != t
is true since long time ago or first visit; that will get page from server. Then diff is less than 10s andx == t
, that will make theelse
part add query strings tohref
andsrc
having sources to refresh.The refresh() function can be called by a button or other conditioned ways. Full control is managed by refining exclusion and inclusion of urls in your code.
对于 Angular 用户,如此处所示,您可以执行以下操作:
解释:Angular
不使用 Angular
显然,“通过帖子获取文件确实会清除缓存的文件,并且它似乎可以在任何浏览器中工作”,
因此使用“he fetch api with POST”也应该可以工作
For angular users and as found here, you can do the following:
explanation: Angular
Not using Angular
Apparently, "Fetching the file by post does clear the cached file and it seems to work in any browser"
So using "he fetch api with POST" should also work
接受的答案
location.reload(true);
不起作用。原因如下(直接取自 MDN 页面):不过,您可能会在现有代码中遇到 location.reload(true) 的实例,这些代码是假设强制重新加载效果发生在所有浏览器中而编写的。 GitHub“location.reload(true)”搜索返回数十万结果。所以有很多现有的代码都包含它。
它的历史是:Netscape Navigator 的某些版本添加了对它的支持,显然最终在 Firefox 中得到了支持。 W3C Web API 工作组一度考虑将其添加到 location.reload() 规范中。然而,它从未被实际添加。
因此,布尔参数不是当前 location.reload() 规范的一部分,而且事实上从未成为任何已发布的 location.reload() 规范的一部分。
来源:https://developer.mozilla.org/en- US/docs/Web/API/Location/reload
那么,如何强制硬刷新呢?两个想法:
使用查询字符串,如本线程中多个其他答案中建议/解释/演示的那样;
请求充斥着 W3C。
https://www.w3.org/Consortium/contact
(有建议 # 2 几年前就被广泛采用,我们几年前就可以停止使用查询字符串 hack。)
The accepted answer
location.reload(true);
DOES NOT WORK. Here's why (taken directly from the MDN page):You may, though, come across instances of location.reload(true) in existing code that was written with the assumption the force-reload effect occurs in all browsers. A GitHub "location.reload(true)" search returns several hundred thousand results. So there's a lot of existing code which has it.
The history of it is: some version of Netscape Navigator added support for it, which apparently eventually got picked up in Firefox. And at one point the W3C Web APIs Working Group took up an issue to consider adding it to the specification for location.reload(). However, it was never actually added.
So a boolean parameter is not part of the current specification for location.reload() — and in fact has never been part of any specification for location.reload() ever published.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload
So, how to force a hard refresh? Two ideas:
Use query strings, as suggested/explained/demoed in multiple other answers in this thread;
Flood the W3C with requests.
https://www.w3.org/Consortium/contact
(Had suggestion #2 been widely adopted years ago, we could have stopped using the query string hack years ago.)
location.reload(true)
已被弃用,因此没有直接的硬重新加载选项,但我们仍然可以手动清除缓存,然后重新加载。请改用此自定义函数。
如果您不想立即刷新而只是清除缓存,请使用
clearCache(false)
希望它能有所帮助,因为上述选项都不适合我。
The
location.reload(true)
is deprecated so there is no direct option to hard reload but we can still manually clear the cache and then reload.Use this custom function instead.
If you don't want to refresh immidiately and just clear the cache, use
clearCache(false)
Hope it helps as none of the above options worked for me.
我发现的最可靠的方法是通过向查询字符串添加值来使用 Chache Buster。
这是我使用的通用例程:
调用此例程将产生类似以下内容:
重新加载后。
这可以强制每次重新加载,但需要注意的是 URL 会发生变化。在大多数应用程序中,这并不重要,但如果服务器依赖于特定参数,这可能会导致潜在的副作用。
The most reliable way I've found is to use a chache buster by adding a value to the querystring.
Here's a generic routine that I use:
Calling this will produce something like this:
after a reload.
This works to force reload every time, but the caveat is that the URL changes. In most applications this won't matter, but if the server relies on specific parameters this can cause potential side effects.
尝试:
当此方法接收
true
值作为参数时,它将导致页面始终从服务器重新加载。如果为 false 或未指定,浏览器可能会从缓存中重新加载页面。详细信息:
Try:
When this method receives a
true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.More info: