如何用JavaScript清除浏览器缓存?

我们部署了最新的JavaScript代码,但是我们无法获得最新的JavaScript代码。

编者按:这个问题在以下几个地方有半重复,下面第一个问题的答案可能是最好的。这个公认的答案不再是理想的解决方案。

如何强制浏览器重新加载缓存的CSS/JS文件?

如何强制客户端刷新JavaScript文件?

动态重载本地Javascript源/ json数据


当前回答

Cache.delete()可以用于新的chrome, firefox和opera。

其他回答

尝试更改JavaScript文件的src?从这个:

<script language="JavaScript" src="js/myscript.js"></script>

:

<script language="JavaScript" src="js/myscript.js?n=1"></script>

这个方法应该强制浏览器加载JS文件的新副本。

大多数正确答案在这个话题中已经提到了。然而,我想添加一篇文章的链接,这是我能读到的最好的一篇文章。

https://www.fastly.com/blog/clearing-cache-browser

在我看来,最合适的解决方案是:

POST在一个iframe中。下面是建议帖子的一个小删减:

=============

const ifr = document.createElement('iframe');
ifr.name = ifr.id = 'ifr_'+Date.now();
document.body.appendChild(ifr);
const form = document.createElement('form');
form.method = "POST";
form.target = ifr.name;
form.action = ‘/thing/stuck/in/cache’;
document.body.appendChild(form);
form.submit();

有一些明显的副作用:这将创建一个浏览器历史记录条目,并受到响应未缓存的相同问题的影响。但它逃脱了fetch存在的预飞行要求,并且由于它是一个导航,分割缓存的浏览器将清除正确的缓存。

这个几乎能搞定。Firefox将为跨源资源保留卡住的对象,但仅用于后续获取。每个浏览器都将使对象的导航缓存无效,无论是同一源资源还是跨源资源。

==============================

我们尝试了很多方法,但是这个很有效。唯一的问题是,你需要能够以某种方式将这个脚本带到最终用户页面,这样你就能够重置缓存。在这种特殊情况下,我们是幸运的。

你不能用javascript清除缓存。 一种常见的方法是将修订号或最近一次更新的时间戳附加到文件中,如下所示:

myscript.123.js

or

myscript.js吗?更新= 1234567890

除了每小时或每周缓存一次之外,您还可以根据文件数据进行缓存。

示例(PHP):

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

甚至使用文件修改时间:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

请不要提供错误的信息。 缓存api是一种不同于http缓存类型的缓存

当服务器发送正确的头文件时,HTTP缓存被触发,你不能用javasvipt访问。

另一方面,缓存api在你想要的时候被触发,它在与service worker一起工作时很有用,所以你可以从这种类型的缓存中交叉请求和回答它 参见:插图1插图2课程

你可以使用这些技巧让你的用户总是有新鲜的内容:

Use location.reload(true) this does not work for me, so I wouldn't recomend it. Use Cache api in order to save into the cache and intersect the request with service worker, be carefull with this one because if the server has sent the cache headers for the files you want to refresh, the browser will answer from the HTTP cache first, and if it does not find it, then it will go to the network, so you could end up with and old file Change the url from you stactics files, my recomendation is you should name it with the change of your files content, I use md5 and then convert it to string and url friendly, and the md5 will change with the content of the file, there you can freely send HTTP cache headers long enough

我建议你看第三部