Skip to content

Commit

Permalink
currentScript hook to try document.currentScript before lastScript
Browse files Browse the repository at this point in the history
  • Loading branch information
Joel Chen committed Sep 13, 2023
1 parent dcd8f31 commit 2808413
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 6 additions & 0 deletions docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ This hook could be asynchronous and you can fetch asynchronously some data and r

Note that this hook does not apply to [module types](module-types.md), which use the default browser fetch implementation.

#### getCurrentScript() -> HTMLScriptElement | null

This function returns `document.currentScript` if it's defined, else it tries to look for the last script tag.

This is used when a SystemJS module is being loaded and registered with the `<script>` tag, such that SystemJS needs to get the element to the script to get its `src` attribute.

#### prepareImport() -> Promise

This function is called before any `System.import` or dynamic import, returning a Promise that is resolved before continuing to perform the import.
Expand Down
16 changes: 14 additions & 2 deletions src/features/script-load.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,26 @@ systemJSPrototype.createScript = function (url) {
return script;
};

systemJSPrototype.getCurrentScript = function() {
if (hasDocument) {
var lastScript = document.currentScript;
if (!lastScript) {
var scripts = document.querySelectorAll('script[src]');
lastScript = scripts[scripts.length - 1];
}
return lastScript;
}

return null;
}

// Auto imports -> script tags can be inlined directly for load phase
var lastAutoImportUrl, lastAutoImportDeps, lastAutoImportTimeout;
var autoImportCandidates = {};
var systemRegister = systemJSPrototype.register;
systemJSPrototype.register = function (deps, declare) {
if (hasDocument && document.readyState === 'loading' && typeof deps !== 'string') {
var scripts = document.querySelectorAll('script[src]');
var lastScript = scripts[scripts.length - 1];
var lastScript = this.getCurrentScript();
if (lastScript) {
lastAutoImportUrl = lastScript.src;
lastAutoImportDeps = deps;
Expand Down

0 comments on commit 2808413

Please sign in to comment.