How can I force clients to refresh JavaScript files?

后端 未结 26 2202
旧时难觅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:09

    Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files.

    For example, to force the file to be cached for no longer than 1 day, you would send:

    Cache-Control: max-age=86400, must-revalidate
    

    For beta, if you want to force the user to always get the latest, you would use:

    Cache-Control: no-cache, must-revalidate
    
    0 讨论(0)
  • 2020-11-22 04:10

    Google Page-Speed: Don't include a query string in the URL for static resources. Most proxies, most notably Squid up through version 3.0, do not cache resources with a "?" in their URL even if a Cache-control: public header is present in the response. To enable proxy caching for these resources, remove query strings from references to static resources, and instead encode the parameters into the file names themselves.

    In this case, you can include the version into URL ex: http://abc.com/v1.2/script.js and use apache mod_rewrite to redirect the link to http://abc.com/script.js. When you change the version, client browser will update the new file.

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

    You can add file version to your file name so it will be like:

    https://www.example.com/script_fv25.js
    

    fv25 => file version nr. 25

    And in your .htaccess put this block which will delete the version part from link:

    RewriteEngine On
    RewriteRule (.*)_fv\d+\.(js|css|txt|jpe?g|png|svg|ico|gif) $1.$2 [L]
    

    so the final link will be:

    https://www.example.com/script.js
    
    0 讨论(0)
  • 2020-11-22 04:12

    The common practice nowadays is to generate a content hash code as part of the file name to force the browser especially IE to reload the javascript files or css files.

    For example,

    vendor.a7561fb0e9a071baadb9.js
    main.b746e3eb72875af2caa9.js

    It is generally the job for the build tools such as webpack. Here is more details if anyone wants to try out if you are using webpack.

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

    For ASP.NET I suppose next solution with advanced options (debug/release mode, versions):

    Js or Css files included by such way:

    <script type="text/javascript" src="Scripts/exampleScript<%=Global.JsPostfix%>" />
    <link rel="stylesheet" type="text/css" href="Css/exampleCss<%=Global.CssPostfix%>" />
    

    Global.JsPostfix and Global.CssPostfix is calculated by the following way in Global.asax:

    protected void Application_Start(object sender, EventArgs e)
    {
        ...
        string jsVersion = ConfigurationManager.AppSettings["JsVersion"];
        bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings["UpdateJsEveryAppStart"]);
        int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;
        JsPostfix = "";
    #if !DEBUG
        JsPostfix += ".min";
    #endif      
        JsPostfix += ".js?" + jsVersion + "_" + buildNumber;
        if (updateEveryAppStart)
        {
            Random rand = new Random();
            JsPosfix += "_" + rand.Next();
        }
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 04:13

    We have been creating a SaaS for users and providing them a script to attach in their website page, and it was not possible to attach a version with the script as user will attach the script to their website for functionalities and i can't force them to change the version each time we update the script

    So, we found a way to load the newer version of the script each time user calls the original script

    the script link provided to user

    <script src="https://thesaasdomain.com/somejsfile.js" data-ut="user_token"></script>
    

    the script file

    if($('script[src^="https://thesaasdomain.com/somejsfile.js?"]').length !== 0) {
       init();
    } else {
       loadScript("https://thesaasdomain.com/somejsfile.js?" + guid());
    }
    
    var loadscript = function(scriptURL) {
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = scriptURL;
       head.appendChild(script);
    }
    
    var guid = function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
    
    var init = function() {
        // our main code
    }
    

    Explanation:

    The user have attached the script provided to them in their website and we checked for the unique token attached with the script exists or not using jQuery selector and if not then load it dynamically with newer token (or version)

    This is call the same script twice which could be a performance issue, but it really solves the problem of forcing the script to not load from the cache without putting the version in the actual script link given to the user or client

    Disclaimer: Do not use if performance is a big issue in your case.

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