-
Notifications
You must be signed in to change notification settings - Fork 31
cachebusting
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.
HTML5 Boilerplate comes with server configuration files: .htaccess
, web.config
and nginx.conf
. These files tell the server to add JavaScript and CSS cache control.
Traditionally, if you use a far future Expires header you have to change the component's filename whenever the component changes.
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 update those resources.
<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">
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.
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 Revving Filenames: don’t use querystring, 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 its default configuration is unreliable for this method. Since Squid Proxy version 2.7 (released May 31 2008) the change is no longer necessary as described in Squid Wiki: Caching Dynamic Content.
Bottom line: Query string cachebusting is not guaranteed to work for all your visitors.