Components.utils.import
was introduced in Firefox 3 and is used for sharing code between different scopes easily. For example, you can import XPCOMUtils.jsm to avoid copy/pasting long XPCOM component registration boilerplate in your component files.
See Using JavaScript code modules for more details.
Note: Prior to Gecko 2.0, JavaScript code modules could only be loaded using file: or resource: URLs. Gecko 2.0 adds support for loading modules from chrome: URLs, even those inside JAR archives.
Components.utils.import(url [, scope]); // Or, if you use a tool such as jslint which reports compiler errors for the above, Components.utils["import"](url [, scope]);
url
scope
Under Boot2Gecko, the scope is not optional. If your code is meant to work on all platforms, you should always provide a scope.
In case of doubt, this
is generally a good scope.
import throws if it encounters an error (like a syntax error) in the file it reads.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", this);
The differences from mozIJSSubScriptLoader
:
The behavior when importing/loading the same code from different locations:
Components.utils.import
evaluates the code of each module only once, in its own scope.For example:
var scope1 = {}, scope2 = {}; Components.utils.import("resource://gre/modules/JSON.jsm", scope1); Components.utils.import("resource://gre/modules/JSON.jsm", scope2); assert(scope2.XPCOMUtils === scope1.XPCOMUtils);
...returns true
, whereas:
var someURL = "resource://gre/modules/JSON.jsm"; var obj1 = {}, obj2 = {}; var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader); loader.loadSubScript(someURL, obj1); loader.loadSubScript(someURL, obj2); assert(obj2 === obj1);
...returns false
.
This means Components.utils.import
is better suited for efficient sharing of code (and data?) between JS scripts running in different scope.
js/xpconnect/tests/unit/