How can I force clients to refresh JavaScript files?

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

    FRONT-END OPTION

    I made this code specifically for those who can't change any settings on the backend. In this case the best way to prevent a very long cache is with:

    new Date().getTime()
    

    However, for most programmers the cache can be a few minutes or hours so the simple code above ends up forcing all users to download "the each page browsed". To specify how long this item will remain without reloading I made this code and left several examples below:

    // cache-expires-after.js v1
    function cacheExpiresAfter(delay = 1, prefix = '', suffix = '') { // seconds
        let now = new Date().getTime().toString();
        now = now.substring(now.length - 11, 10); // remove decades and milliseconds
        now = parseInt(now / delay).toString();
        return prefix + now + suffix;
    };
    
    // examples (of the delay argument):
    // the value changes every 1 second
    var cache = cacheExpiresAfter(1);
    // see the sync
    setInterval(function(){
        console.log(cacheExpiresAfter(1), new Date().getSeconds() + 's');
    }, 1000);
    
    // the value changes every 1 minute
    var cache = cacheExpiresAfter(60);
    // see the sync
    setInterval(function(){
        console.log(cacheExpiresAfter(60), new Date().getMinutes() + 'm:' + new Date().getSeconds() + 's');
    }, 1000);
    
    // the value changes every 5 minutes
    var cache = cacheExpiresAfter(60 * 5); // OR 300
    
    // the value changes every 1 hour
    var cache = cacheExpiresAfter(60 * 60); // OR 3600
    
    // the value changes every 3 hours
    var cache = cacheExpiresAfter(60 * 60 * 3); // OR 10800
    
    // the value changes every 1 day
    var cache = cacheExpiresAfter(60 * 60 * 24); // OR 86400
    
    // usage example:
    let head = (document.head || document.getElementsByTagName('head')[0]);
    let script = document.createElement('script');
    script.setAttribute('src', '//unpkg.com/sweetalert@2.1.2/dist/sweetalert.min.js' + cacheExpiresAfter(60 * 5, '?'));
    head.append(script);
    
    // this works?
    let waitSwal = setInterval(function() {
        if (window.swal) {
            clearInterval(waitSwal);
            swal('Script successfully injected', script.outerHTML);
        };
    }, 100);
    

提交回复
热议问题