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

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

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

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

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

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


当前回答

把这个放在模板的末尾:

var scripts =  document.getElementsByTagName('script');
var torefreshs = ['myscript.js', 'myscript2.js'] ; // list of js to be refresh
var key = 1; // change this key every time you want force a refresh
for(var i=0;i<scripts.length;i++){ 
   for(var j=0;j<torefreshs.length;j++){ 
      if(scripts[i].src && (scripts[i].src.indexOf(torefreshs[j]) > -1)){
        new_src = scripts[i].src.replace(torefreshs[j],torefreshs[j] + 'k=' + key );
        scripts[i].src = new_src; // change src in order to refresh js
      } 
   }
}

其他回答

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

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');
?>

...剩下的程序…

我花了一些时间来解决这个问题(因为许多浏览器对不同的命令有不同的行为,但它们都检查文件的时间,并将其与浏览器中下载的副本进行比较,如果日期和时间不同,将进行刷新),如果你不能按照假设的正确方式进行,总有另一种可用的更好的解决方案。祝你露营愉快。

更新:请参见location.reload()没有参数作为这个非标准参数的背景,以及Firefox如何可能是唯一支持的现代浏览器。


您可以调用window.location.reload(true)来重新加载当前页面。它将忽略任何缓存项,并从服务器检索页面、css、图像、JavaScript等的新副本。这不会清除整个缓存,但会清除您所在页面的缓存。

但是,最好的策略是对路径或文件名进行版本控制,就像在其他各种答案中提到的那样。此外,请参阅旋转文件名:由于不使用?v=n作为版本控制方案的原因,不要使用querystring。

这是我在我的最新项目中使用的一个片段。

来自控制器:

if ( IS_DEV ) {
    $this->view->cacheBust = microtime(true);
} else {
    $this->view->cacheBust = file_exists($versionFile) 
        // The version file exists, encode it
        ? urlencode( file_get_contents($versionFile) )
        // Use today's year and week number to still have caching and busting 
        : date("YW");
}

从视图来看:

<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">

我们的发布过程生成一个包含当前版本版本号的文件。这是通过URL编码文件,并使用它作为缓存破坏者。作为故障转移,如果该文件不存在,则使用年和周数,以便缓存仍能工作,并且至少每周刷新一次。

此外,这为开发环境中的每个页面加载提供了缓存破坏,这样开发人员就不必担心为任何资源(javascript、css、ajax调用等)清除缓存。

由于浏览器缓存相同的链接,您应该在url末尾添加一个随机数。 new Date(). gettime()生成一个不同的数字。

只需添加新的Date().getTime()链接结束 调用

'https://stackoverflow.com/questions.php?' + new Date().getTime()

输出:https://stackoverflow.com/questions.php?1571737901173