On 11/13/12 10:27, Archaeopteryx wrote:
Hi,

what is the recommend way to import JavaScript code modules in files
part of Gecko?

1) Don't add the import line
Components.utils.import("resource://app/my_module.jsm"); into the file
if the module has already been loaded by a different JavaScript file
load earlier.
Advantage: Fastest
Disadvantage: If the other file drops the jsm, the code will break. The
developer will have to find the issue if the file requiring the jsm gets
loaded into a different scope and won't work (e.g. by an extension).

2) Conditional loading by checking if the exported symbol(s) exist:
if (!exportedSymbol)
     Components.utils.import("resource://app/my_module.jsm");

3) Add the import line on top of the file:
Components.utils.import("resource://app/my_module.jsm");

https://developer.mozilla.org/en-US/docs/JavaScript_code_modules/Using
reads:

"An extremely important behavior of Components.utils.import() is that
modules are cached when loaded and subsequent imports do not reload a
new version of the module, but instead use the previously cached version."

So are 2) and 3) nearly equivalent regarding performance? What is the
recommend way to import a JavaScript module?

I'd expect some slight overhead of 3, but not very much, and assuming you aren't doing this in a loop probably negligible.

If you are really talking about Gecko code, then just do 1. Simple and if anything elsewhere in the file changes then tests should catch it and it can be corrected.

If you're talking about extensions running in window context though you might want to import to your own context to be sure nothing else takes it away:

var scope = {};
Components.utils.import("resource://app/my_module.jsm", scope);
scope.foo();

_______________________________________________
dev-platform mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to