search

Home  >  Q&A  >  body text

Wait for the script with type="module" to complete before running the next script

At the bottom of the body tag inside my html document, I have 2 script tags with type="module". There is a script tag below that contains some embed code that depends on the results of the first two scripts.

Is there a way to ensure that this code is only executed after the first two scripts have completed?

<script src="./src/js/script1.js" type="module"></script>
<script src="./src/js/script2.js" type="module"></script>
<script type="text/javascript">
  // Code inside this tag should only run after the 2 previous script tags have been executed
  console.log('Hello SO');
</script>

P粉739706089P粉739706089324 days ago509

reply all(1)I'll reply

  • P粉127901279

    P粉1279012792024-02-18 10:42:18

    <script> Tags with type="module" will automatically be assigned the defer attribute (see Script loading and execution order ), so in order for the third label to run later, it also needs to be deferred. Since this is not possible with inline scripts (as mentioned in the comments), you can either move the script to another file and reference it using the src attribute, or wrap the code in DOMContentLoaded In the event listener for the event (see https://stackoverflow.com/a/41395202/19461620)

    Use external script file:

    sssccc

    script.js

    // Code inside this tag should only run after the 2 previous script tags have been executed
      console.log('Hello SO');

    Using DOMContentLoaded Callback:

    sssccc

    reply
    0
  • Cancelreply