doushifen4060 2015-07-11 19:27
浏览 113
已采纳

禁用动态创建的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. 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. This problem appear on Chrome and IE, on Firefox everything working fine.

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)

I've tried many different Header() PHP settings it's doesn't change anything.

PS: I can't use random number like test.js?r=923902390 to do the trick i need another solution

  • 写回答

2条回答 默认 最新

  • dongya5893 2015-07-13 22:46
    关注

    Idea 1 (basic)

    Generate the content randomness within javascript on the client side. Make javascript work a little more. This is probably what should be done. It's more reasonable. Unless it's just not possible.

    Idea 2 (less reasonable and probably overengineered)

    Make the script check its own url and load another (randomized) copy of itself.

    // 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 flask项目,怎么使用AJAX传数据库数据到echarts图表的data里,实现异步加载数据。
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?