jrburke/requirejs — pull request #1146 by arendjr (2014-06-06 11:50:00+00:00)
Title: Allow Require.js to re-use existing script nodes.

For my website, I'm using both Require.js and a Grunt-based build system. I have an index.html file which loads the CSS and require.js, then configures Require.js through inline script and finally bootstraps the application by requiring two modules ("app" and "libs") and finally instantiating the Application object defined in the "app" module. Later on, additional modules may be required which are outside the scope of this discussion (but may be relevant if you question why I would want to keep using Require.js in this use case).

This setup results in the following flow of requests:

index.html
+-- all.css
+-- require.js
+-- app.js
+-- libs.js

Now, I decided to try if I could optimize this by including app.js and libs.js straight from the HTML. My Grunt-based build system has all the knowledge about the built modules, and because I know upfront which modules are going to required for sure, I might be able to speed things up by instructing the browser to load these modules as soon as possible.

All said and done, I've included two async script statements in my index.html and now my request flow looks like this:

index.html
+-- all.css
+-- require.js
+-- app.js
+-- libs.js

This gives a significant speedup in the loading of resources, and in my specific case even resulted in a 80ms speedup under ideal circumstances. Ideal means both the server and browser are running on the same machine so there is no latency. Admittedly I was surprised the gain was this big too (I had mainly expected the gains to be in scenarios where latency is high), but it must have something to do with the browser being able to parallelize more work now.

However, there was one problem, which was that Require.js was unaware that app.js and libs.js were already being loaded and would try to insert its own script tags as well, which resulted in inconsistent JS errors depending on the order in which files were now included. The fix was to make Require.js aware of the script tags that were already there, and not attempt to add new ones and duplicate the nodes. This pull request provides that fix. Hopefully it will be useful to others as well.

Cheers,
Arend jr.