Drew Noakes
Drew Noakes

Reputation: 311127

RequireJS data-main with query string not working

To avoid the browser caching my optimised JS bundle, I'd like to include an MD5 sum on the request URL. I tried something like:

<script src="lib/require.js" data-main="app/main.js?md5=ABCD"></script>

However the introduction of the query string causes a GET request to /main.js. That is, the query string is missing and even scripts is missing from the path.

How can I force the request for the script specified in data-main to be loaded with the hash that I've calculated? Note that the markup is being generated, so I can inject the hash anywhere in the HTML document.

Upvotes: 4

Views: 1283

Answers (1)

Drew Noakes
Drew Noakes

Reputation: 311127

The trick is to use the urlArgs configuration setting. So, in this example the code should resemble:

<script>
require = {
    urlArgs: 'md5=ABCD'
};
</script>
<script src="lib/require.js" data-main="app/main.js"></script>

Make sure you define the global require object before loading the require.js library.

This works because RequireJS runs the following code when it starts up (as of v2.1.10, see line 190 of the unminified source):

//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
    //assume it is a config object.
    cfg = require;
    require = undefined;
}

Check your browser's dev tools and you should see the the arguments on the query string:

enter image description here

Upvotes: 5

Related Questions