Pinion v1.1: cache busting

Pipit Pinion v1.1 introduces a new feature: cache busting.

What is cache busting?

Caching assets is a common practice. You can, for example, set your server to tell the browser to cache CSS files for a period of time (month/year/etc). Plus browsers do some caching by default so a returning user doesn’t have to download these files every time they visit your website.

So what happens if you update a CSS file (without changing the file name)? If there’s a cached copy, the browser uses it instead of the updated one as the browser sees it as the same file.

What you want here is for the browser to download the updated file instead of using the cached copy. Cache busting is making the browser disregard the cached copy and download the updated file.

What does this feature do?

It adds a timestamp of the last time the file was modified to your link tags. So if you’re file is /assets/css/styles.css, Pinion outputs the tag as:

<link rel="stylesheet" href="/assets/css/styles.1511342726.css" type="text/css">

Your file name remains as is styles.css, but the browser sees it as styles.1511342726.css. When you modify the file, the link tag will have a different timestamp so the browser thinks it’s a new file and as a result will download the updated file.

In order for the above to work, you need to add the following to your .htaccess:

RewriteRule ^(.+)\.(\d+)\.(js|css)$ $1.$3 [L]

How to use:

You can tell Pinion to add the timestamp to the files by using the cache-bust option. Setting it to true applies the timestamps to all included file in that call:

    'cache-bust' => true,

You can use an array so it is only applied to some files. The following example adds all CSS files in the directory assets/vendor (and its sub-directories), but only applies the timestamp to 2 files:

    'dir' => 'assets/vendor',
    'cache-bust' => ['prism/prism.min.css', 'demo.css'],

More details on how to use this feature in the documentation.

Do you need to use this feature?

It’s up to you to evaluate your needs.

If you are already handling renaming your file with a task manager like Gulp or Grunt (using gulp-cache-bust or grunt-cache-bust), then there’s no need to use this feature.

If you are adding a version to your file name (e.g. styles.v2.0.css), then you shouldn’t to use this feature.

If your files are named like styles.css, this is for you.