[英]Disable cache for dynamic created Javascript
I've created a dynamic javascript (test.js) file in PHP with Symfony2 and i do not want this file to be cached by browser. 我已经用Symfony2在PHP中创建了一个动态javascript(test.js)文件,但我不希望该文件被浏览器缓存。 When i insert the script test.js 2 times in one page, the first time it's loading directly from the server but for the second time the script is loaded from browser cache. 当我在一个页面中两次插入脚本test.js时,第一次是直接从服务器加载脚本,而第二次是从浏览器缓存加载脚本。 This problem appear on Chrome and IE, on Firefox everything working fine. 此问题出现在Chrome和IE上,在Firefox上一切正常。
Here a live example : http://goo.gl/sggKks (if you see 3 time same number that mean it's loaded from cache, if 3 different numbers it's loaded from server) 这是一个实时示例: http : //goo.gl/sggKks (如果您看到3次表示从缓存中加载的相同数字,如果您从服务器中加载了3个不同的数字)
I've tried many different Header() PHP settings it's doesn't change anything. 我尝试了许多不同的Header()PHP设置,但它没有任何改变。
PS: I can't use random number like test.js?r=923902390 to do the trick i need another solution PS:我不能使用test.js?r = 923902390这样的随机数来解决问题,我需要其他解决方案
If you cannot add a dynamic parameter in the URL (event if I think it's the best way to achieve what you want to do), you can disable the cache with .htaccess like this : 如果您不能在URL中添加动态参数(如果我认为这是实现所需功能的最佳方法,则可以这样做),您可以使用.htaccess禁用缓存,如下所示:
<filesMatch "\.js$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
You need to activate the Apache Header module. 您需要激活Apache Header模块。
If you cannot use this, you should define your JS file as a route in Symfony, and set these headers in your controller response. 如果无法使用此功能,则应在Symfony中将JS文件定义为路由,并在控制器响应中设置这些标头。
Generate the content randomness within javascript on the client side. 在客户端的javascript中生成内容随机性。 Make javascript work a little more. 使javascript工作更多。 This is probably what should be done. 这可能是应该做的。 It's more reasonable. 比较合理 Unless it's just not possible. 除非这是不可能的。
Make the script check its own url and load another (randomized) copy of itself. 使脚本检查其自己的URL并加载其自身的另一个(随机)副本。
// self contained auto cloning facility
(function(){
// see http://www.2ality.com/2014/05/current-script.html
var currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
// get script tag url (self)
var url = currentScript.getAttribute('src');
// url doesn't have random part
if(!url.match(/\?\d+$/)) {
// create new script tag with random part
var s = document.createElement('script');
s.src = url+'?'+Math.round(Math.random()*1000000000);
document.body.appendChild(s);
// engage wild brakes
throw "stop";
}
})();
// do the actual job below this point
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.