How can I force clients to refresh JavaScript files?

后端 未结 26 2203
旧时难觅i
旧时难觅i 2020-11-22 03:40

We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slo

相关标签:
26条回答
  • 2020-11-22 04:24

    My colleague just found a reference to that method right after I posted (in reference to css) at http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/. Good to see that others are using it and it seems to work. I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

    0 讨论(0)
  • 2020-11-22 04:26

    For ASP.NET pages I am using the following

    BEFORE

    <script src="/Scripts/pages/common.js" type="text/javascript"></script>
    

    AFTER (force reload)

    <script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>
    

    Adding the DateTime.Now.Ticks works very well.

    0 讨论(0)
  • 2020-11-22 04:26

    The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.

    This is how I did it:

    $(document).ready(function(){
        $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
             startProgram();
        });
    });
    

    Check the function at http://api.jquery.com/jQuery.getScript/

    By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

    0 讨论(0)
  • 2020-11-22 04:28

    This usage has been deprected: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

    This answer is only 6 years late, but I don't see this answer in many places... HTML5 has introduced Application Cache which is used to solve this problem. I was finding that new server code I was writing was crashing old javascript stored in people's browsers, so I wanted to find a way to expire their javascript. Use a manifest file that looks like this:

    CACHE MANIFEST
    # Aug 14, 2014
    /mycode.js
    
    NETWORK:
    *
    

    and generate this file with a new time stamp every time you want users to update their cache. As a side note, if you add this, the browser will not reload (even when a user refreshes the page) until the manifest tells it to.

    0 讨论(0)
  • 2020-11-22 04:28

    Athough it is framework specific, Django 1.4 has this functionailty which works in a similar fashion to the link to the 'greenfelt' site in the above answer

    0 讨论(0)
  • 2020-11-22 04:30

    Simplest solution? Don't let the browser cache at all. Append the current time (in ms) as a query.

    (You are still in beta, so you could make a reasonable case for not optimizing for performance. But YMMV here.)

    0 讨论(0)
提交回复
热议问题