0

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?

3
  • as the main concept, this is the best way for handle this, if you searched for a package or something out of the box that handles this you could use webpack Commented Jan 21, 2020 at 18:43
  • 1
    Yeah, webpack (webpack.js.org) would handle this issue as well, but I didn't need the other features, and wanted something really simple. Commented Jan 21, 2020 at 19:10
  • if you want it simple so your solution is enough for this Commented Jan 21, 2020 at 19:56

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.