使用 Javascript 加载没有缓存的外部 <script>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14897849/
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-26 22:52:37  来源:igfitidea点击:

Load external <script> without cache using Javascript

javascriptjquery

提问by Ni Le

I want to load an external javascript file into the page and make sure its not cached. I do not have access to php so I cant generate a random string after the filename.

我想将外部 javascript 文件加载到页面中并确保它没有被缓存。我无权访问 php,因此无法在文件名后生成随机字符串。

In PHP the script would look like this:

在 PHP 中,脚本如下所示:

<script src="http://site.com/cool.js?<?php echo $randomnumber; ?>"></script>

Is there a way to do something like that using only javascript?

有没有办法只使用 javascript 来做类似的事情?

回答by epascarello

Use jQuery's getScriptinstead of a script tag.

使用 jQuery 的getScript代替脚本标签。

$.getScript("http://example.com/cool.js");

or pure JavaScript

或纯 JavaScript

var scr = document.createElement("script");
scr.src = "http://example.com/cool.js" + "?ts=" + new Date().getTime();
document.getElementsByTagName("head")[0].appendChild(scr);

回答by marekful

Just append a random string to the srcof the script like you do with PHP. For this you need to inject the <script>tag with JS.

只需src像使用 PHP 一样将一个随机字符串附加到脚本的 。为此,您需要<script>使用 JS注入标签。

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'path/to/file?' + new Date().getMilliseconds();

document.getElementsByTagName('head')[0].appendChild(s);

回答by Marc B

Sure, just insert a script tag into the DOM, with JS generating the value, e.g.

当然,只需在 DOM 中插入一个脚本标签,由 JS 生成值,例如

var d = new Date.getTime();
$('head').append('<scri' + 'pt src="http://....?cachebuster=' + d + '"></scr' + 'ipt>');

回答by jonasnas

You can try <meta http-equiv="Cache-Control" content="no-store" />. There is another ticket talking about this: stackoverflow

你可以试试<meta http-equiv="Cache-Control" content="no-store" />。还有另一张票在谈论这个:stackoverflow