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>
<script>
Tags withtype="module"
will automatically be assigned thedefer
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 thesrc
attribute, or wrap the code inDOMContentLoaded
In the event listener for the event (see https://stackoverflow.com/a/41395202/19461620)Use external script file:
script.js
Using
DOMContentLoaded
Callback: