How to force loading of JS and CSS files with each new published version?

12

Every time I publish a new version of my web application (a multi-company system) that has changes in JS and CSS files, some clients complain about errors and I find that it is the cache of the browser and I have to instruct the client to refresh the page with ctrl F5 .

I wonder if there is a way for me to force the browser to fetch the JS and CSS files on the server every time I publish a new version (perhaps saving a cookie on the client stating the version last time it was accessed and compare to each load).

I searched Google and found no information that really helped. My application is in C # .Net.

    
asked by anonymous 03.09.2015 / 20:57

2 answers

7

Concatenate any random numbers that vary with each upload at the end of the file extension.

EX: style.css? v = 1651516151;

    
03.09.2015 / 22:44
7

In PHP using the timestamp of the file you know if it has undergone any changes, forcing a new load, if it is not changed it will still handle what is already in the browser cache.

With php do so, but you can use the same idea for your language.

example:

<link rel="stylesheet" href="css/style.css?v=<?php echo filemtime('css/style.css'); ?>">

In the browser it will look like this:

<link rel="stylesheet" href="/css/estilo.css?v=1429015974" />

In JS would be using a function to generate a number (date & timestamp) to be added at the end of the file.

Example:

<script type="text/javascript">

    function addcss(css){
        var d = new Date();
        var n = d.getTime();
        var head = document.getElementsByTagName('head')[0];
        var s = document.createElement('link');
        s.setAttribute('rel', 'stylesheet');
        s.setAttribute('href', css+'?v='+n)
        head.appendChild(s);
    }   

    //chame a função passando o caminho do CSS ou JS 
    addcss('css/style.css');
</script>

The output will be:

<link rel="stylesheet" href="css/style.css?v=1457636631802">
    
10.03.2016 / 19:33