Craft Environmental Cacheing
Monday, 16 January 2017 by Ian Ebden
Looks like this article is over a year old, so some of the technical solutions or opinions may be a bit outdated now.
We all know how important performance is when it comes to the user experience these days, not to mention search engine ranking; and there are a ton of tips and techniques we can use to make our pages fly. Plus, browsers like Chrome do an excellent job of cacheing static assets like images and scripts, helping to reduce HTTP requests.
All of this is very welcome but it can be problematic during development, when you or your client need to preview changes and you have to resort to manually clearing the browser's cache to see those changes.
There are Craft plugins available (including this one) that can help. But I always like to find a plugin-free solution when I can, so here's a simple technique you might want to try.
I like to use a version number for cache busting and control, outputting something like:
Adding a query string with a new version (e.g. 1.1) means most browsers will download a fresh copy of your file. We can use Craft and Twig to set our query string and control cacheing.
I’m using a ternary operator to output my query string. On the development environment this will be a randomly generated string, ensuring the browser grabs a new file each time the page is loaded. Meanwhile the production environment will output a string from a variable called assetVersion
. This is a global variable set in Craft's general.php config file:
Now we can bust the cache in browsers when viewing our development site so we always see the latest changes to static assets like CSS. Meanwhile our assets get cached on production, helping to speed up our pages. When we deploy updates to production we simply update our assetVersion
and browsers grab the new assets.
End