CSS Cache Busting And Drupal
I realized in my last post i alluded to a strategy for build based CSS cache busting with Drupal but did not explain it, so here goes.
With Drupal or any other similar system you are going to wind up with a lot of CSS, and for the most part you want this to be cached by the user to speed up load times. However when you deploy new code, you definitely want the CSS to be refreshed.
To address this issue we take advantage of a browsers default behavior of not caching files with different names by adding a query to the end of the css call.
Our basic approach is to have the build number or revision somewhere and insert that into our CSS calls.
We first define a variable in index.php at the root of the project with a token that ANT will replace with a build number.
This is what is in my index.php file:
define('BUILD_REVISION', '@build-revision@');
The ant task looks like this:
replace file="${temp.dir}${cache.buster.file.path}"
token="@build-revision@"
value="${Revision}"Revision is from Subversion.
Whenever we call a CSS file we need to reference the constant we just defined for example:
<link rel="stylesheet" href="<?= base_path() . path_to_theme() ?>/css/sugababes.css?< ?=BUILD_REVISION?>" type="text/css" media="screen" />
</link>
Now whenever you do a build a revision is added to the end of the CSS call.
/css/sugababes.css?420247
The browsers will now update the CSS file whenever you deploy a new version of the project.
If you just do a SVN checkout or do not use ANT on your workstation copy, everything will still work fine you will just have the token rather than the build number appended to your CSS.
There may be an alternative method where you extend drupal_add_css to automatically append the token and if you are using Drupal long term you should probably investigate that
Recent Comments