How can I force clients to refresh JavaScript files?

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

    
    

    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.

提交回复
热议问题