Skip to content

Instantly share code, notes, and snippets.

@erikvold
Created June 19, 2011 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save erikvold/1034614 to your computer and use it in GitHub Desktop.
Save erikvold/1034614 to your computer and use it in GitHub Desktop.
Imports a commonjs style javascript file with loadSubScrpt for restartless Firefox add-ons.
/* Imports a commonjs style javascript file with loadSubScrpt
* By Erik Vold <erikvvold@gmail.com> http://erikvold.com/
*
* @param src (String)
* The url of a javascript file.
*/
(function(global) {
var modules = {};
global.require = function require(src) {
if (modules[src]) return modules[src];
var scope = {require: global.require, exports: {}};
var tools = {};
Components.utils.import("resource://gre/modules/Services.jsm", tools);
var baseURI = tools.Services.io.newURI(__SCRIPT_URI_SPEC__, null, null);
try {
var uri = tools.Services.io.newURI(
"packages/" + src + ".js", null, baseURI);
tools.Services.scriptloader.loadSubScript(uri.spec, scope);
} catch (e) {
var uri = tools.Services.io.newURI(src, null, baseURI);
tools.Services.scriptloader.loadSubScript(uri.spec, scope);
}
return modules[src] = scope.exports;
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment