Skip to content
VSEphpbb edited this page Feb 21, 2012 · 4 revisions

Version Control with Cachebusting

Why do you need to cache JavaScript and CSS?

Web page designs are getting richer and richer, which means more scripts and stylesheets in the page. A first-time visitor to your page may have to make several HTTP requests, but by using the Expires header you make those components cacheable. This avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often used with images, but they should be used on all components including scripts, stylesheets etc.

How does HTML5 Boilerplate handle JavaScript and CSS cache?

HTML5 Boilerplate comes with server configuration files: .htacess, web.config and nginx.conf. These files tell the server to add JavaScript and CSS cache control.

When do you need to use version control with cachebusting?

Traditionally, if you use a far future Expires header you have to change the component's filename whenever the component changes.

How to use cachebusting?

The H5BP .htaccess has built-in filename cache busting. To use it, uncomment the following lines in the .htaccess file:

<IfModule mod_rewrite.c>
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
</IfModule>

This will route all requests to /path/filename.20120101.ext to /path/filename.ext. To use this, just add a time-stamp number (or your own numbered versioning system) into your resource filenames in your HTML source whenever you up date those resources. Examples:

<script type="text/javascript" src="/js/myscript.20120305.js"></script>
<script type="text/javascript" src="/js/jqueryplugin.45.js"></script>
<link rel="stylesheet" href="css/somestyle.49559939932.css">
<link rel="stylesheet" href="css/anotherstyle.2.css">

Do I have to rename the resource on the filesystem as well?

No. The whole purpose of this cachebusting method is that you can leave your Javascript and CSS file names alone. All you have to do is add the timestamp number to the filename in your HTML source. The .htaccess directive will serve up the proper file.

What about file?v=1231 ?

Traditional cachebusting involved adding a query string to the end of your JavaScript or CSS filename whenever you updated it:

<script type="text/javascript" src="/js/all.js?v=12"></script>

However, as Steve Souders explains in this article, the query string approach is not reliable for clients behind a Squid Proxy Server. The proxy server can be configured to work with this form of cachebusting, but it's default configuration is unreliable for this method. Bottom line: Query string cachebusting is not guaranteed to work for all your visitors.

Clone this wiki locally