Prevent RequireJS from Caching Required Scripts

BumbleB2na picture BumbleB2na · Nov 29, 2011 · Viewed 107.7k times · Source

RequireJS seems to do something internally that caches required javascript files. If I make a change to one of the required files, I have to rename the file in order for the changes to be applied.

The common trick of appending a version number as a querystring param to the end of the filename does not work with requirejs <script src="jsfile.js?v2"></script>

What I am looking for is a way to prevent this internal cacheing of RequireJS required scripts without having to rename my script files every time they are updated.

Cross-Platform Solution:

I am now using urlArgs: "bust=" + (new Date()).getTime() for automatic cache-busting during development and urlArgs: "bust=v2" for production where I increment the hard-coded version num after rolling out an updated required script.

Note:

@Dustin Getz mentioned in a recent answer that Chrome Developer Tools will drop breakpoints during debugging when Javascript files are continuously refreshed like this. One workaround is to write debugger; in code to trigger a breakpoint in most Javascript debuggers.

Server-Specific Solutions:

For specific solutions that may work better for your server environment such as Node or Apache, see some of the answers below.

Answer

Phil McCullick picture Phil McCullick · Dec 12, 2011

RequireJS can be configured to append a value to each of the script urls for cache busting.

From the RequireJS documentation (http://requirejs.org/docs/api.html#config):

urlArgs: Extra query string arguments appended to URLs that RequireJS uses to fetch resources. Most useful to cache bust when the browser or server is not configured correctly.

Example, appending "v2" to all scripts:

require.config({
    urlArgs: "bust=v2"
});

For development purposes, you can force RequireJS to bypass the cache by appending a timestamp:

require.config({
    urlArgs: "bust=" + (new Date()).getTime()
});