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

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

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

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

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

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


当前回答

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

来自控制器:

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

你也可以用元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>

它会刷新并避免缓存,但它会在你的页面上,直到你完成测试,然后你可以把它拿掉。第一个选择是最好的选择。

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

来自控制器:

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调用等)清除缓存。

window.location.reload(true)似乎已经被HTML5标准弃用了。不使用查询字符串的一种方法是使用Clear-Site-Data报头,这似乎是标准化的。

在PHP中,你也可以强制每小时重新加载一次代码,就像这样:

<?php
echo '<script language="JavaScript" src="js/myscript.js?token='.date('YmdH').'">';
?>

or

<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>