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 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示