防止缓存 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15277786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:10:07  来源:igfitidea点击:

Preventing Cache on JavaScript files

javascriptgoogle-chromecaching

提问by Ryan Fitzgerald

I'm trying to prevent 2 JavaScript files from being cached by the browser.

我试图阻止浏览器缓存 2 个 JavaScript 文件。

I've tryed to use <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">without success. Here's my <head>element code:

我尝试使用<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">但没有成功。这是我的<head>元素代码:

    <head>

<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="NO-CACHE">

<link type='text/css' href='/files/theme/popup_basic.css' rel='stylesheet' media='screen' />

<!-- JavaScript Start -->
<script type="text/javascript" src="/files/theme/gohome.js"></script>
<script type="text/javascript" src="http://192.168.0.149/redirect.js"></script>
<!-- JavaScript End -->

</head>

From my understating, this should work. But the redirect.jsfile keeps being cached!

从我的理解来看,这应该有效。但是redirect.js文件一直被缓存!

Anyone know what I'm doing wrong?

有谁知道我做错了什么?

回答by Derek

The <meta http-equiv="Cache-control" content="NO-CACHE">, the directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server.

<meta http-equiv="Cache-control" content="NO-CACHE">不应该使用NO-CACHE缓存的指示信息,而是请求应被转发到源服务器:,指令缓存控制。

In order to prevent cache on every request, you may need to add some random string in url. The example below is use javascript to dynamic create a script tag and adding random number in the url, then append it.

为了防止每次请求都缓存,您可能需要在 url 中添加一些随机字符串。下面的例子是使用javascript动态创建一个脚本标签并在url中添加随机数,然后附加它。

<script language="JavaScript">
 var s=document.getElementsByTagName('script')[0];
 var sc=document.createElement('script');
 sc.type='text/javascript';
 sc.async=true;
 sc.src='http://192.168.0.149/redirect.js?v' + Math.random(); 
 s.parentNode.insertBefore(sc,s);
</script>

If just want to prevent 1 time only, just append some string to the src.

如果只想阻止 1 次,只需在 src 中附加一些字符串。

<script src="http://192.168.0.149/redirect.js?12345678"></script>