Skip to content

Commit 51539ef

Browse files
authored
Cleanup code for capturing document.currentScript in MODULARIZE mode. (#24535)
This refactor makes it clear exactly if/when we need the extra closure. It also elides the closure completely when one is not needed.
1 parent 3e1cffc commit 51539ef

File tree

3 files changed

+18
-21
lines changed

3 files changed

+18
-21
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1277
1+
1263
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
2618
1+
2588

tools/link.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2479,27 +2479,24 @@ def modularize():
24792479
'generated_js': generated_js,
24802480
}
24812481

2482-
if settings.MINIMAL_RUNTIME and not settings.PTHREADS and not settings.WASM_WORKERS:
2483-
# Single threaded MINIMAL_RUNTIME programs do not need access to
2484-
# document.currentScript, so a simple export declaration is enough.
2482+
# In MODULARIZE mode this JS may be executed later, after
2483+
# document.currentScript is gone, so we need to capture it on load using a
2484+
# closure. In EXPORT_ES6 mode we can just use 'import.meta.url'.
2485+
capture_currentScript = settings.ENVIRONMENT_MAY_BE_WEB and not settings.EXPORT_ES6
2486+
# Single threaded MINIMAL_RUNTIME programs do not need access to
2487+
# document.currentScript, so a simple export declaration is enough.
2488+
if settings.MINIMAL_RUNTIME and not settings.PTHREADS:
2489+
capture_currentScript = False
2490+
2491+
if not capture_currentScript:
24852492
src = f'var {settings.EXPORT_NAME} = {wrapper_function};'
24862493
else:
2487-
script_url_web = ''
2488-
# When MODULARIZE this JS may be executed later,
2489-
# after document.currentScript is gone, so we save it.
2490-
# In EXPORT_ES6 mode we can just use 'import.meta.url'.
2491-
if settings.ENVIRONMENT_MAY_BE_WEB and not settings.EXPORT_ES6:
2492-
script_url_web = "var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;"
2493-
src = '''\
2494-
var %(EXPORT_NAME)s = (() => {
2495-
%(script_url_web)s
2496-
return (%(wrapper_function)s);
2497-
})();
2498-
''' % {
2499-
'EXPORT_NAME': settings.EXPORT_NAME,
2500-
'script_url_web': script_url_web,
2501-
'wrapper_function': wrapper_function,
2502-
}
2494+
src = f'''\
2495+
var {settings.EXPORT_NAME} = (() => {{
2496+
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
2497+
return ({wrapper_function});
2498+
}})();
2499+
'''
25032500

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

0 commit comments

Comments
 (0)