Skip to content

Instantly share code, notes, and snippets.

@noamr
Last active August 23, 2023 16:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamr/756d349e2a9457c643837eab1143dc0e to your computer and use it in GitHub Desktop.
Save noamr/756d349e2a9457c643837eab1143dc0e to your computer and use it in GitHub Desktop.
A polyfill for script element loading (for illustration purposes)
function parseHTML(getNextElement) {
let doneParsing = null;
const whenDoneParsing = new Promise(resolve => { doneParsing = resolve; });
while (const element = getNextElement()) {
if (element.tagName !== "SCRIPT") {
// parse everything else...
continue;
}
const whenSourceLoaded = fetch(element.src).then(response => response.text());
if (element.async) {
whenSourceLoaded.then(eval);
} else if (element.type === "module" || element.defer) {
Promise.all([whenSourceLoaded, whenDoneParsing]).then(([source]) => eval(source));
} else {
eval(await whenSourceLoaded);
}
}
// This will execute all scripts that are already loaded in the same task
doneParsing();
}
@mmocny
Copy link

mmocny commented Mar 15, 2023

Do all module scripts actually run before all deferred (if they are loaded by the parse is complete)?

@noamr
Copy link
Author

noamr commented Mar 15, 2023

Do all module scripts actually run before all deferred (if they are loaded by the parse is complete)?

Yes! Though I think it's a Chromium thing rather than a standard thing
https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/script/html_parser_script_runner.cc;l=453?q=parser_script_R

@noamr
Copy link
Author

noamr commented Mar 16, 2023

OK

Do all module scripts actually run before all deferred (if they are loaded by the parse is complete)?

OK actually it was a mistake, was thrown off by "force deferred" script which is a non-standard chromium feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment