Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

currentScript hook to try document.currentScript before lastScript #2469

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/hooks.md
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
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