Skip to content

Instantly share code, notes, and snippets.

@prajwalit
Created May 8, 2015 19:21
Show Gist options
  • Save prajwalit/0570797630293fd873fb to your computer and use it in GitHub Desktop.
Save prajwalit/0570797630293fd873fb to your computer and use it in GitHub Desktop.
RequireJS Request Aggregator
/**
* A way to override RequireJS' loader so as to use request combiners
* like - https://github.com/rgrove/combohandler
*
* If you have multiple dependencies, say [a, b, c], requirejs fires
* three requests. This modification will allow you to combine these
* files and make a single request to `combo?a.js&b.js&c.js`
* On server-side, you can use a combohandler to serve concatinated
* files.
*/
(function () {
var COMBO_BASE = "/combo?";
var COMBO_SEPARATOR = "&";
var DEBOUNCE_TIMEOUT = 15;
var collecting = false, collection = [];
var headNode = document.head;
/**
* Takes a collection, builds a combo url, and creates a node
* with load/error handlers
*/
var getComboNode = function (collection) {
var node = document.createElement ("script");
// Create Url
node.src = COMBO_BASE + collection.map (function (coll) {
return coll.url;
}).join (COMBO_SEPARATOR);
// Add Load Handler
node.addEventListener ("load", function (ev) {
collection.forEach (function (coll) {
coll.context.onScriptLoad.call (coll.context, ev);
});
}, false);
// Add Error Handler
node.addEventListener ("error", function (ev) {
collection.forEach (function (coll) {
coll.context.onScriptError.call (coll.context, ev);
});
}, false);
return node;
};
/**
* Override require's load.
* Collects requests for specified timeout.
* Makes a Combo Url Node.
* Appends it to the head.
*/
require.load = function (context, moduleName, url) {
// Keep a collection of context and urls
collection.push ({
context: context,
url: url
});
if (!collecting) {
// Start collecting
collecting = true;
// Add a timeout to stop collecting and fire combo request for
// the current collection.
window.setTimeout (function () {
collecting = false;
headNode.appendChild (getComboNode (collection));
collection = [];
}, DEBOUNCE_TIMEOUT);
}
};
}) ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment