notoriousb1t

Force browser to reload JavaScript and CSS

Do you ever have to tell clients to hit CTRL+F5 to refresh after making changes?  I have a short trick that you can use to force the browser to reload when you make changes.

Here is the trick:

Include this in the page after your title before you load any JavaScript or CSS:

<script type='text/javascript'>  
    (function() {
        var build = '92';
        var lastBuild = localStorage.getItem('build');
        if (lastBuild !== build) {
            localStorage.setItem('build', build);
            location.reload(true);
        }
    }());
</script>  

Change the build each time you publish changes to your JavaScript/CSS.

What is going on exactly?

  • The current build number is declared
  • The last build number is retrieved from local storage in the browser.  Local storage lets you persist information between page visits
  • If the current build and the last don't match, the current build is saved to local storage and the page is reloaded with a hint to clear any cached files and pull everything fresh