Simple cache busting for assets
Want a super basic solution for cache busting local files such as stylesheets and JS files?
I often have to work on old sites that don't benefit from a proper asset pipeline or build tool like Webpack. One of the biggest frustrations with this is when there's no way to cache bust. Normally I utilise webpack's (or Laravel Mix's) version control, which versions the files for me, but on older systems this just isn't an option.
A way around this is to use the last modified time as a nonce in the URL of the file. The simplest way to do this is as a query string.
Below is an example in PHP:
<link rel="stylesheet" href="/assets/css/app.css?v=<?php echo filemtime(__DIR__ . '/assets/css/app.css')); ?>">
You'll need to adjust the path appropriately but hopefully this gives you a good idea of how it works.
filemtime
returns the last modified time from the OS's filesystem as a unix timestamp. This is perfect for cache busting.
If you do have the choice though, I'd always recommend using something slightly more robust like Laravel Mix (which can be used outside of Laravel just fine, it's just some npm packages).