如何用JavaScript清除浏览器缓存?
我们部署了最新的JavaScript代码,但是我们无法获得最新的JavaScript代码。
编者按:这个问题在以下几个地方有半重复,下面第一个问题的答案可能是最好的。这个公认的答案不再是理想的解决方案。
如何强制浏览器重新加载缓存的CSS/JS文件?
如何强制客户端刷新JavaScript文件?
动态重载本地Javascript源/ json数据
如何用JavaScript清除浏览器缓存?
我们部署了最新的JavaScript代码,但是我们无法获得最新的JavaScript代码。
编者按:这个问题在以下几个地方有半重复,下面第一个问题的答案可能是最好的。这个公认的答案不再是理想的解决方案。
如何强制浏览器重新加载缓存的CSS/JS文件?
如何强制客户端刷新JavaScript文件?
动态重载本地Javascript源/ json数据
当前回答
我有一些问题与yboussard建议的代码。内j循环不起作用。下面是我成功使用的修改后的代码。
function reloadScripts(toRefreshList/* list of js to be refresh */, key /* change this key every time you want force a refresh */) {
var scripts = document.getElementsByTagName('script');
for(var i = 0; i < scripts.length; i++) {
var aScript = scripts[i];
for(var j = 0; j < toRefreshList.length; j++) {
var toRefresh = toRefreshList[j];
if(aScript.src && (aScript.src.indexOf(toRefresh) > -1)) {
new_src = aScript.src.replace(toRefresh, toRefresh + '?k=' + key);
// console.log('Force refresh on cached script files. From: ' + aScript.src + ' to ' + new_src)
aScript.src = new_src;
}
}
}
}
其他回答
window.parent.caches.delete("call")
在控制台中执行代码后,关闭并打开浏览器。
你不能用javascript清除缓存。 一种常见的方法是将修订号或最近一次更新的时间戳附加到文件中,如下所示:
myscript.123.js
or
myscript.js吗?更新= 1234567890
试试这个
<script language="JavaScript" src="js/myscript.js"></script>
:
<script language="JavaScript" src="js/myscript.js?n=1"></script>
你也可以用元HTML标签禁用浏览器缓存,只要把HTML标签放在头部部分,以避免网页被缓存,而你正在编码/测试,当你完成时,你可以删除元标签。
(在标题部分)
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0"/>
在头部粘贴后刷新页面,应该也会刷新新的javascript代码。
如果你需要的话,这个链接会给你其他选择 http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags/
或者你可以像这样创建一个按钮
<button type="button" onclick="location.reload(true)">Refresh</button>
它会刷新并避免缓存,但它会在你的页面上,直到你完成测试,然后你可以把它拿掉。第一个选择是最好的选择。
请不要提供错误的信息。 缓存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
我建议你看第三部