Codepen link: https://codepen.io/AnirudhMS/pen/poRmjao?
Code:
console.log('Started script execution.');
(async () => {
let promiseWrapper = async () => {
setTimeout(() => {
console.log("Inside async script.");
Promise.resolve();
}, 0);
};
await promiseWrapper();
})();
console.log('Finished script execution.');
Output:
Started script execution.
Finished script execution.
Inside async script.
Issue:
As can be seen from the above output, in top-level code, the browser does not wait for async operations to finish. Now this also means that an event like dom-ready
will be fired after the synchronous code has finished executing. The problem is not with the is there a way to ensure that the output is as follows:dom-ready
event exactly but
Started script execution.
Inside async script.
Finished script execution.
Edit: Note: The solution needs to work if I replace the setTimeout with an await Promise call!!!
Edit 2:
The solution needs to be such that the dom-ready
event or the DOMContentLoaded
event is fired after the execution of the async script. Is that possible?