load
event listener for async script
This page is served with an script[async]
and then the server
pauses for a specified delay before flushing the rest of the document,
which includes a synchronous inline script
that tries to
listen for the load
event on that script by attaching an
event handler via addEventListener
. The asynchonous script
seems to load in ~125ms when cached, meaning if there is a flush delay
less than that, the event listener will successfully fire. Otherwise, if
the flush delay is greater than that, the load
event will
fire before addEventListener
is called. With cache enabled
and disabled, try loading with 0ms,
100ms, 200ms, and
1000ms.
This also includes an alternative mechanism attaching a
load
event listener via addEventListener
in
which a MutationObserver
is added in an inline blocking
script
that precedes the script[async]
.
This appears to be entirely reliable, even if it is not exactly elegant.
It should work because MutationObserver
is asynchronous but
operates in microtasks, meaning the parsing of script
will be
observed before a subsequent non-microtask task to evaluate the loaded
script
. (Props to
Noam Rosenthal
for this approach.)
⏳ Waiting for script[async]
to evaluate…
⏳ script[async] + script
is waiting for
load
event on script[async]
…
⏳ Waiting for mutation observer to detect
script[async]
and then call
addEventListener('load')
…