Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Ensures a `<script type="module">` tag pointing at `path` exists in `<head>`, loading it as an
- * ES module and resolving once it (or a fallback) has executed.
- *
- * Design notes:
- * - Module scripts are cached by the browser's module map, keyed by the *resolved* URL. Once a
- * module has been fetched/instantiated, re-adding a tag with the same `src` (or clearing and
- * re-setting `src`, as classic scripts allow) does **not** re-run its top-level code — the
- * engine just reuses the cached module record. So, unlike a classic-script loader, we treat an
- * existing matching `<script>` tag as "already loaded" and resolve immediately, rather than
- * trying to force a reload.
- * - `script.src` is always reported by the DOM as an absolute URL, so `path` is resolved against
- * `document.baseURI` before comparing, otherwise a relative `path` would never match an
- * existing absolute `src` and we'd insert duplicate script tags.
- * - If the primary `path` fails to load (e.g. a local/offline asset is missing), we transparently
- * retry once from `altURL` (e.g. a CDN mirror) before rejecting.
- *
- * @param {string} path - Primary module script URL to load (may be relative to the current document).
- * @param {string} altURL - Fallback module script URL to try if `path` fails to load.
- * @returns {Promise<void>} Resolves once a module script (primary or fallback) has loaded;
- * rejects only if both the primary and fallback loads fail.
- */
- function insertScript(path, altURL) {
- return new Promise((resolve, reject) => {
- // Normalize to an absolute URL so it can be compared against existing <script src> values.
- const resolvedPath = new URL(path, document.baseURI).href;
- // Reuse an already-inserted module tag instead of loading the same module twice.
- const existingScript = Array.from(document.head.getElementsByTagName('script')).find(
- (script) => script.src === resolvedPath,
- );
- if (existingScript) {
- // See design notes above: re-triggering `src` would not re-execute an already-cached module.
- resolve();
- return;
- }
- loadModuleScript(resolvedPath, resolve, () => {
- // Primary source failed — fall back to the alternate URL before giving up entirely.
- loadModuleScript(altURL, resolve, reject);
- });
- });
- /**
- * Creates, configures, and appends a single `<script type="module">` element.
- *
- * @param {string} src - The module URL to load.
- * @param {() => void} onSuccess - Invoked once the module has loaded.
- * @param {(error: Error) => void} onFailure - Invoked if the module fails to load.
- * @returns {void}
- */
- function loadModuleScript(src, onSuccess, onFailure) {
- const script = document.createElement('script');
- // `type="module"` gives us native deferred, once-only execution and top-level `import`/`export`.
- script.type = 'module';
- script.src = src;
- script.onload = () => onSuccess();
- script.onerror = () => onFailure(new Error(`Failed to load module script: ${src}`));
- document.head.appendChild(script);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment