<!DOCTYPE html>
<html>
<body>
<h1>The script async attribute</h1>
<p id="p1">Hello World!</p>
<script>alert("execute this second")</script>
<script async>alert("execute this first");</script>
</body>
</html>
I don’t understand why script
tags are executed in order even after using async
keyword. Any help ?
3
Answers
yes, the function is async but it will always start after the code above it has started, you can make it so that the above code starts after some delay like so:-
you can also wrap the code in a function and call it after the async function is executed.
In your example, even though you used async for the second script, there is no guarantee that it will run before the first script. To ensure that the second script runs first, you can use a different approach, like promises or async functions.
Here is an extract of the HTML specification on
async
:In other words: Since
async
is disallowed withoutsrc
(for your type of scripts), it is effectively ignored.That means, both scripts will run synchronously.