Skip to content

Cleanup code for capturing document.currentScript in MODULARIZE mode. #24535

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

Merged
merged 1 commit into from
Jun 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion test/other/codesize/test_codesize_minimal_esm.gzsize
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1277
1263
2 changes: 1 addition & 1 deletion test/other/codesize/test_codesize_minimal_esm.jssize
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2618
2588
35 changes: 16 additions & 19 deletions tools/link.py
Original file line number Diff line number Diff line change
@@ -2488,27 +2488,24 @@ def modularize():
'generated_js': generated_js,
}

if settings.MINIMAL_RUNTIME and not settings.PTHREADS and not settings.WASM_WORKERS:
# Single threaded MINIMAL_RUNTIME programs do not need access to
# document.currentScript, so a simple export declaration is enough.
# In MODULARIZE mode this JS may be executed later, after
# document.currentScript is gone, so we need to capture it on load using a
# closure. In EXPORT_ES6 mode we can just use 'import.meta.url'.
capture_currentScript = settings.ENVIRONMENT_MAY_BE_WEB and not settings.EXPORT_ES6
# Single threaded MINIMAL_RUNTIME programs do not need access to
# document.currentScript, so a simple export declaration is enough.
if settings.MINIMAL_RUNTIME and not settings.PTHREADS:
capture_currentScript = False

if not capture_currentScript:
src = f'var {settings.EXPORT_NAME} = {wrapper_function};'
else:
script_url_web = ''
# When MODULARIZE this JS may be executed later,
# after document.currentScript is gone, so we save it.
# In EXPORT_ES6 mode we can just use 'import.meta.url'.
if settings.ENVIRONMENT_MAY_BE_WEB and not settings.EXPORT_ES6:
script_url_web = "var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;"
src = '''\
var %(EXPORT_NAME)s = (() => {
%(script_url_web)s
return (%(wrapper_function)s);
})();
''' % {
'EXPORT_NAME': settings.EXPORT_NAME,
'script_url_web': script_url_web,
'wrapper_function': wrapper_function,
}
src = f'''\
var {settings.EXPORT_NAME} = (() => {{
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
return ({wrapper_function});
}})();
'''

if settings.SOURCE_PHASE_IMPORTS:
src = f"import source wasmModule from './{settings.WASM_BINARY_FILE}';\n\n" + src