Please join me at my new location

Sunday, December 14, 2008

Javascript Development Tip #1: no-cache

When doing javascript development that requires files to be loaded from an HTTP server, caching can be a real pain. Turning off browser caching is one solution, but I've always had mixed results. The real solution is to turn off caching on the server side. In order to prevent well behaved browsers from caching your files you simply need to add a header to every response.

The HTTP specification has a list of headers that user-agents and servers should understand, however I've always found the headers around caching to be a bit of a black art. However, for our purposes, there's no magic necessary. To tell the browser not to cache resources, the cache-control header must be set to no-cache. This tells the browser not to cache the resource, not in memory, not in disk, just take the response entity, use it and forget you ever received it.

So, how do you go about adding this header to each response? If you're serving your files from Apache, you can use mod_headers. mod_header allows you to add arbitrary headers to responses. The module has a lot of capabilities, but only the basics are required for our purposes.

The first step is to enable the module by adding a line similar to the following to your httpd.conf. Most installations of Apache have this line conmmented out. If that's the case, just uncomment it.

LoadModule headers_module modules/

With the module enabled, you can have to modify the headers of outgoing responses. If can be configured server-wide, within a virtual host, a directory using .htaccess. You can also enable it in <Directory>, <Location>, and <Files> sections. Whichever you choose, just add the following line, save your changes and restart the server.

Header set cache-control "no-cache"

This tells mod_headers to set the cache-control header to no-cache for all responses within its configured scope. If the cache-control header has already been set, it will be overriden by the value you've specified.

To verify that the configuration worked, clear your browsers cache and make a request to one of the resources covered by the configuration of mod_headers. If you're using Firefox and have Firebug installed, you can switch to the Net tab and look at the response headers.

So there you have it, an easy way to speed up development and reduce your stress by simply removing caching, the real way.