Visit Mozilla.org

Components.utils.import

From MDC

This article covers features introduced in Firefox 3


This method 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.

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

See Using_JavaScript_code_modules for documentation.

[edit] 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.

  • The subscript loader accepts a URL to the code to load, while import only accepts resource: and file: URIs.

[edit] Additional Resources