Stop JavaScript from being cached.

This is a guide on how to stop JavaScript from being cached by the browser. As you probably already know, having functionality “break” because the user’s browser is using an old cached file can be pretty frustrating.

In this guide, we will look at two different methods. There are two ways to do this:

  1. Completely stop all caching of our JavaScript files or
  2. Force the browser to use the newest version of our JS file.

Use the latest version.

The best method is to force the browser to use the newest version. We can do this by appending the version number of the file as a query string parameter:

If the JS file goes unchanged, then the user’s browser will continue to cache it. However, if we update the file, then we can simply change the version parameter from 1.12 to something such as 1.13 or 1.14 (I typically use the version number that is present in my version control software – GIT, SVN, etc). Changing the version number will “bust the cache” by tricking the browser into thinking that it is a completely new file. The only drawback of this method is that you will have to modify the page that is including the script.

Never cache the file.

If you want to make sure that your visitors are always using an uncached version of your JavaScript, then you can simply use a server side language such as PHP to append the current timestamp as a query string. Here is a simple example:

In the script above, we use PHP to output the current UNIX timestamp as a query string parameter. Because the timestamp value changes every second, it ensures that the user’s browser will always look for the newest uncached version of our JavaScript file.