Ben in CA
Ben in CA

Reputation: 851

Forcing cache update of prior version of css / javascript with PHP

There's many Q&A's about how to prevent users' browsers from caching old versions of JS and CSS files.

For frequent users of a web app, I want those files to be cached, but when I update the JS / CSS content, then I want the user to automatically fetch the new version.

No doubt others have also used something similar, but I didn't like most of the suggestions I found, and I came up with this:

<?php $css_last_mod = filemtime("path_to/styles.css"); ?>
<link href="path_to/styles.css?v=<?php echo $css_last_mod; ?>" rel="stylesheet" />

Include this in your header, and the CSS file's last modified timestamp will only change when the file is updated. (and thus indicate to the browser that there's a new version)

<link href="includes_public/styles.css?v=1579628430" rel="stylesheet">

And of course the same concept can be used for JS files.

Are there any known compatibility issues with this?

Upvotes: 0

Views: 369

Answers (1)

Capitex
Capitex

Reputation: 133

No, there's no compatibility issues with that; I use that with every webapp and I don't have issues. This is my code, I always force to no cache

<script type="text/javascript">
    var time = new Date();
    var js = ['a','c','d']; //this is my js files
    var style = ['s','mtto'];//this is my css files
    for(var i=0; i<js.length; i++){
        var js_element = document.createElement('script');
        js_element.src = 'js/'+js[i]+'.js?x='+time.getTime();
        document.head.appendChild(js_element);
    }
    for(var i=0; i<style.length; i++){
        var importedStyle = document.createElement('link');
        importedStyle.rel = 'stylesheet';
        importedStyle.href = ''+style[i]+'.css?x='+time.getTime();
        document.head.appendChild(importedStyle);
    }
</script>

Upvotes: 1

Related Questions