jsloader-api.rst (2403B)
1 JS Loader APIs 2 ============== 3 4 Gecko provides multiple ways to load/evaluate JS files from JS files, 5 in addition to standard ways such as the dynamic ``import()`` and the worker's 6 ``importScripts``. 7 8 Synchronous Classic Script Load 9 ------------------------------- 10 11 ``Services.scriptloader.loadSubScript`` can be used for synchronously loading 12 given classic script in the given global. 13 14 The script is evaluated in the 2nd parameter's global, and the loaded script's 15 global variables are defined into the given object. 16 17 .. code:: JavaScript 18 19 Services.scriptloader.loadSubScript( 20 "chrome://browser/content/browser.js", this 21 ); 22 23 See `mozIJSSubScriptLoader.idl <https://searchfox.org/mozilla-central/source/js/xpconnect/idl/mozIJSSubScriptLoader.idl>`_ for more details 24 25 Asynchronous Classic Script Compile 26 ----------------------------------- 27 28 ``ChromeUtils.compileScript`` can be used for asynchronously compile given 29 classic script, and execute in given globals. 30 31 .. code:: JavaScript 32 33 async function f() { 34 const script = await ChromeUtils.compileScript( 35 "resource://test/some_script.js" 36 ); 37 38 const result = script.executeInGlobal(targetGlobal1); 39 40 // The script can be executed against multiple globals. 41 const result2 = script.executeInGlobal(targetGlobal2); 42 } 43 44 See `ChromeUtils.webidl <https://searchfox.org/mozilla-central/source/dom/chrome-webidl/ChromeUtils.webidl>`_ and `PrecompiledScript.webidl <https://searchfox.org/mozilla-central/source/dom/chrome-webidl/PrecompiledScript.webidl>`_ for more details. 45 46 Synchronous Module Import 47 ------------------------- 48 49 ``ChromeUtils.importESModule`` and ``ChromeUtils.defineESModuleGetters`` can be used for importing ECMAScript modules into the current global. 50 51 The last parameter of those API controls where to import the module. 52 Passing ``{ global: "current" }`` option makes it to import the module into the current global. 53 54 .. code:: JavaScript 55 56 const { Utils } = 57 ChromeUtils.importESModule("resource://gre/modules/Utils.sys.mjs", { 58 global: "current", 59 }); 60 61 Utils.hello(); 62 63 const lazy = {} 64 ChromeUtils.defineESModuleGetters(lazy, { 65 Utils2: "resource://gre/modules/Utils2.sys.mjs", 66 }, { 67 global: "current", 68 }); 69 70 function f() { 71 lazy.Utils2.hello(); 72 } 73 74 See :ref:`System Modules <System Modules>` for more details about those API.