Consider the following JSBin (content pasted below as well).
You can see that the window load event is fired before the module with a top-level await has finished. I've observed a similar thing when using the load event of a script tag.
Is there an equivalent event that would wait for a module with a top-level await to have completed?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id='async' type="module">
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
window.addEventListener('load', function () {
document.body.innerHTML += 'async: Window load event fired</br>';
});
document.body.innerHTML += 'async: Starting module</br>';
document.body.innerHTML += `async: Long op</br>`;
const now = (new Date()).getTime();
await sleep(1000);
document.body.innerHTML += `async: Finished module ${(new Date()).getTime() - now}</br>`;
</script>
<script id='sync' type="module">
window.addEventListener('load', function () {
document.body.innerHTML += 'sync: Window load event fired</br>';
});
document.body.innerHTML += 'sync: Starting module</br>';
document.body.innerHTML += `sync: Long op</br>`;
const now = (new Date()).getTime();
const a = [];
for(let i = 0; i < 10000000; i++){
a[i] = i^2;
}
document.body.innerHTML += `sync: Finished module ${(new Date()).getTime() - now}</br>`;
</script>
</body>
</html>