|
| 1 | +# Dynamic script loader |
| 2 | + |
| 3 | +The optional C++ `DynamicScriptLoader` plugin installs `_native.loadScript(name)`, which returns a promise that settles after evaluating source in the current JavaScript context. The host supplies a resolver that returns either a JavaScript string or a promise of a string. Missing resources (null or undefined), rejected lookups, and evaluation errors reject the returned promise. No file or network loader is installed by JsRuntimeHost. |
| 4 | + |
| 5 | +```cpp |
| 6 | +#include <Babylon/Plugins/DynamicScriptLoader.h> |
| 7 | + |
| 8 | +Babylon::Plugins::DynamicScriptLoader::Initialize(env, |
| 9 | + [](Napi::Env env, const std::string& name) -> Napi::Value { |
| 10 | + auto source = FindPackagedScript(name); |
| 11 | + return source ? Napi::String::New(env, *source) : env.Null(); |
| 12 | + }); |
| 13 | +``` |
| 14 | +
|
| 15 | +Initialize the plugin after `JsRuntime` and before evaluating the entry bundle. Link the `DynamicScriptLoader` target; `JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER` controls whether it is built. It uses the existing `_native` object and does not install global `loadScript`, `importScripts`, or native `import()` syntax. Names must be nonempty strings without NUL characters; source containing NUL characters is rejected because the evaluation API accepts null-terminated strings. Empty source is allowed. |
| 16 | +
|
| 17 | +The resolver runs on the JavaScript thread. For asynchronous resolvers, return `Napi::Promise::Deferred::Promise()` and resolve it with source on a later JavaScript dispatch turn, or reject it with the lookup error. The host must stop asynchronous producers before destroying the runtime; it must not access Node-API values or dispatch through a destroyed runtime. The loader does not cache scripts or cancel host operations. |
| 18 | +
|
| 19 | +## Bundled imports |
| 20 | +
|
| 21 | +The runtime plugin is bundler-independent: it evaluates classic scripts, not untransformed ECMAScript modules. A bundler transforms source-level `import()` and manages exports, dependencies, caching, and concurrent imports. Its chunk transport must call `_native.loadScript` instead of a browser or filesystem loader. |
| 22 | +
|
| 23 | +### Webpack 5 example |
| 24 | +
|
| 25 | +The following `webpack.config.cjs` is an application-side example, not a separate JsRuntimeHost build package. It keeps Webpack's chunk registration and adds the host evaluation promise to the promises each import already waits for. JsRuntimeHost supplies `window` as an alias for the script global; no document is required. |
| 26 | +
|
| 27 | +```js |
| 28 | +module.exports = { |
| 29 | + entry: "./src/index.js", |
| 30 | + target: ["web", "es5"], |
| 31 | + mode: "production", |
| 32 | + devtool: false, |
| 33 | + output: { |
| 34 | + filename: "entry.js", |
| 35 | + chunkFilename: "[name].js", |
| 36 | + chunkFormat: "array-push", |
| 37 | + chunkLoading: "jsonp", |
| 38 | + globalObject: "window", |
| 39 | + publicPath: "", |
| 40 | + }, |
| 41 | + plugins: [{ |
| 42 | + apply(compiler) { |
| 43 | + const { RuntimeGlobals, RuntimeModule } = compiler.webpack; |
| 44 | + compiler.hooks.thisCompilation.tap("HostScriptLoading", compilation => { |
| 45 | + compilation.hooks.runtimeModule.tap("HostScriptLoading", module => { |
| 46 | + if (module.name === "load script") { |
| 47 | + module.generate = () => ""; |
| 48 | + } |
| 49 | + }); |
| 50 | + compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.loadScript) |
| 51 | + .tap("HostScriptLoading", chunk => { |
| 52 | + const runtime = new RuntimeModule("host script loading", RuntimeModule.STAGE_ATTACH + 1); |
| 53 | + runtime.generate = () => ` |
| 54 | +var loads = Object.create(null); |
| 55 | +${RuntimeGlobals.loadScript} = function(name, done) { |
| 56 | + var load = loads[name] = Promise.resolve().then(function() { |
| 57 | + return _native.loadScript(name); |
| 58 | + }); |
| 59 | + load.then(function() { |
| 60 | + done({ type: "load", target: { src: name } }); |
| 61 | + }, function() { |
| 62 | + done({ type: "error", target: { src: name } }); |
| 63 | + }); |
| 64 | +}; |
| 65 | +var ensureChunk = ${RuntimeGlobals.ensureChunkHandlers}.j; |
| 66 | +${RuntimeGlobals.ensureChunkHandlers}.j = function(chunkId, promises) { |
| 67 | + ensureChunk(chunkId, promises); |
| 68 | + var load = loads[${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)]; |
| 69 | + if (load) { |
| 70 | + promises.push(load); |
| 71 | + } |
| 72 | +};`; |
| 73 | + compilation.addRuntimeModule(chunk, runtime); |
| 74 | + }); |
| 75 | + }); |
| 76 | + }, |
| 77 | + }], |
| 78 | +}; |
| 79 | +``` |
| 80 | + |
| 81 | +Initialize the runtime plugin before evaluating `entry.js`. Package every emitted JavaScript chunk under its emitted relative name; the host resolver decides which names are accepted. For browser builds, omit the example's plugin and use the normal browser output settings. Other bundlers need their own chunk-transport integration. |
| 82 | + |
| 83 | +The import promise waits for both chunk registration and complete script evaluation. Lookup and evaluation failures reject it; successful evaluation without the expected registration rejects with Webpack's `ChunkLoadError`. Failed lookups can be retried. Evaluation failure after registration is not rolled back; discard the runtime if that failure leaves application state unusable. |
| 84 | + |
| 85 | +This example uses classic JavaScript chunks only. Do not combine it with hot module replacement, a development server, browser prefetch/preload hints, CSS chunk loading, or native-module externals. The host must complete or reject each resource operation; no timeout is added. Select source transpilation appropriate for the engine: Webpack's `target` controls its generated runtime, not all syntax in application source. |
0 commit comments