skip to Main Content
<!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


  1. 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:-

    <!DOCTYPE html>
    <html lang="en"> 
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
    </head>
    <body>
    <script>
        setTimeout(()=>{
            alert("this will be executed after")
        },1000)
    </script>
    <script async>
        alert("this will be executed first")
    </script>
    </body>
    </html>
    

    you can also wrap the code in a function and call it after the async function is executed.

    Login or Signup to reply.
  2. 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.

    async function executeScripts() {
            await new Promise((resolve,rejected) => {
              setTimeout(() => {
                alert('execute this first');
                resolve();
              }, 0);
            });
    
            alert('execute this second');
          }
    
          executeScripts();
    <!DOCTYPE html>
    <html>
      <body>
        <h1>The script async attribute</h1>
        <p id="p1">Hello World!</p>
      </body>
    </html>
    Login or Signup to reply.
  3. Here is an extract of the HTML specification on async:

    Classic scripts may specify … async, but must not specify [it]
    unless the src attribute is present. Module scripts may specify
    the async attribute (…).

    In other words: Since async is disallowed without src (for your type of scripts), it is effectively ignored.

    That means, both scripts will run synchronously.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search