Created
May 8, 2015 19:21
-
-
Save prajwalit/0570797630293fd873fb to your computer and use it in GitHub Desktop.
RequireJS Request Aggregator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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