如何用JavaScript清除浏览器缓存?
我们部署了最新的JavaScript代码,但是我们无法获得最新的JavaScript代码。
编者按:这个问题在以下几个地方有半重复,下面第一个问题的答案可能是最好的。这个公认的答案不再是理想的解决方案。
如何强制浏览器重新加载缓存的CSS/JS文件?
如何强制客户端刷新JavaScript文件?
动态重载本地Javascript源/ json数据
如何用JavaScript清除浏览器缓存?
我们部署了最新的JavaScript代码,但是我们无法获得最新的JavaScript代码。
编者按:这个问题在以下几个地方有半重复,下面第一个问题的答案可能是最好的。这个公认的答案不再是理想的解决方案。
如何强制浏览器重新加载缓存的CSS/JS文件?
如何强制客户端刷新JavaScript文件?
动态重载本地Javascript源/ json数据
当前回答
尝试更改JavaScript文件的src?从这个:
<script language="JavaScript" src="js/myscript.js"></script>
:
<script language="JavaScript" src="js/myscript.js?n=1"></script>
这个方法应该强制浏览器加载JS文件的新副本。
其他回答
Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:
<?php
touch('/www/control/file1.js');
touch('/www/control/file2.js');
touch('/www/control/file2.js');
?>
...剩下的程序…
我花了一些时间来解决这个问题(因为许多浏览器对不同的命令有不同的行为,但它们都检查文件的时间,并将其与浏览器中下载的副本进行比较,如果日期和时间不同,将进行刷新),如果你不能按照假设的正确方式进行,总有另一种可用的更好的解决方案。祝你露营愉快。
Cache.delete()可以用于新的chrome, firefox和opera。
你不能用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>
我已经通过使用解决了这个问题 ETag
Etag类似于指纹,如果给定URL上的资源发生变化,则必须生成一个新的Etag值。比较它们可以确定资源的两个表示是否相同。