Components.utils.import

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.

Syntax

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]);

Parameters

url
A string of the URL of the script to be loaded. The URL must point to a file on the disk, possibly in a JAR.
scope
An optional object to import onto; if omitted, the global object is used.

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.

return value
the module's global object.
use of the return value is discouraged since it grants access to the module's internal properties which are not part of its public API.

import throws if it encounters an error (like a syntax error) in the file it reads.

Example

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm", this);

Difference from mozIJSSubScriptLoader

The differences from mozIJSSubScriptLoader:

The behavior when importing/loading the same code from different locations:

  • the subscript loader evaluates the specified code each time it is invoked, with the caller's global object.
  • 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.

Additional Resources

Document Tags and Contributors

 Last updated by: marco-c,