-
-
Save johan/1152970 to your computer and use it in GitHub Desktop.
Imports a commonjs style javascript file with loadSubScrpt for restartless Firefox add-ons.
This file contains hidden or 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
/* Imports a commonjs style javascript file with loadSubScrpt | |
* By Erik Vold <[email protected]> http://erikvold.com/ | |
* | |
* @param src (String) | |
* The url of a javascript file. | |
*/ | |
(function(global) { | |
var modules = {} | |
, tools = {} | |
, baseURI, io, js; | |
Components.utils.import("resource://gre/modules/Services.jsm", tools); | |
js = tools.Services.scriptloader; | |
io = tools.Services.io; | |
baseURI = io.newURI(__SCRIPT_URI_SPEC__, null, null); | |
global.require = function require(src) { | |
if (modules[src]) return modules[src]; | |
var scope = { require: global.require | |
, exports: {} | |
} | |
, uri; | |
try { | |
uri = io.newURI("packages/" + src + ".js", null, baseURI); | |
js.loadSubScript(uri.spec, scope); | |
} catch (e) { | |
uri = io.newURI(src, null, baseURI); | |
js.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
I'm not sure if this is better than Erik's original, where we reimport Services.jsm on every require() call, or worse, for holding a reference to stuff imported from that module for the life-time of the code we get embedded in.
(I have no idea whether Erik wants his attribution to remain as is even when other people have been poking around with the code, making it only "based on code by Erik Vold". I personally think code with name tags creates more politics and problems than value, but try to stay out of the debate, where I can. Don't blame Erik for my tweaks. :-)