Skip to content

Instantly share code, notes, and snippets.

@johan
Forked from erikvold/require.js
Created August 18, 2011 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johan/1152970 to your computer and use it in GitHub Desktop.
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.
/* 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 = {}
, 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);
@johan
Copy link
Author

johan commented Aug 18, 2011

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. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment