如何使用 javascript 和基本脚本加载强制不缓存

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

How to force no cache using javascript and basic script loading

javascriptcachingsrc

提问by ParoX

I have a bookmarklet that keeps using cache versions of http://www.imvu-e.com/products/hpv/download/HPV.js. I want it to never cache it and always reload it.

我有一个一直使用缓存版本的书签http://www.imvu-e.com/products/hpv/download/HPV.js。我希望它永远不会缓存它并始终重新加载它。

This is the hyperlink I use to save the bookmarklet (which users drag to browser toolbar that installs it):

这是我用来保存书签的超链接(用户将其拖到安装它的浏览器工具栏):

<a href="javascript:(function(){
     c = document.createElement(&quot;script&quot;);
     c.type = &quot;text/javascript&quot;;
     c.src = &quot;http://www.imvu-e.com/products/hpv/download/HPV.js&quot;;

     c.onload = c.onreadystatechange = function()                    {
            if ( ! (d = this.readyState) || d == &quot;loaded&quot; || d == &quot;complete&quot;){
                document.documentElement.childNodes[0].removeChild(c);
                version='beta';
            }
     };
     document.documentElement.childNodes[0].appendChild(c);
})();">Run HPV</a>

回答by Prescott

Add a useless querystring to the end of your url:

在 url 末尾添加一个无用的查询字符串:

c.src = "http://www.imvu-e.com/products/hpv/download/HPV.js?" + (new Date).getTime(); 

回答by ahankendi

Use jQuery's getScript instead of a script tagging and altering the source

使用 jQuery 的 getScript 而不是标记和更改源的脚本

<script>
   $.getScript("JavascriptFileName.js?timestamp=" + new Date().getTime());
</script>

回答by Arthur Costa

Pure JS solution:

纯JS解决方案:

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