How to force the browser to reload cached CSS/JS files?

后端 未结 30 4403
青春惊慌失措
青春惊慌失措 2020-11-21 05:49

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even be

30条回答
  •  旧时难觅i
    2020-11-21 06:06

    Here is a pure JavaScript solution

    (function(){
    
        // Match this timestamp with the release of your code
        var lastVersioning = Date.UTC(2014, 11, 20, 2, 15, 10);
    
        var lastCacheDateTime = localStorage.getItem('lastCacheDatetime');
    
        if(lastCacheDateTime){
            if(lastVersioning > lastCacheDateTime){
                var reload = true;
            }
        }
    
        localStorage.setItem('lastCacheDatetime', Date.now());
    
        if(reload){
            location.reload(true);
        }
    
    })();
    

    The above will look for the last time the user visited your site. If the last visit was before you released new code, it uses location.reload(true) to force page refresh from server.

    I usually have this as the very first script within the so it's evaluated before any other content loads. If a reload needs to occurs, it's hardly noticeable to the user.

    I am using local storage to store the last visit timestamp on the browser, but you can add cookies to the mix if you're looking to support older versions of IE.

提交回复
热议问题