Home > Software engineering >  Wait for scripts with type="module" to finish before running the next script
Wait for scripts with type="module" to finish before running the next script

Time:01-06

At the bottom of the body tag inside my html document I have 2 script tags with type="module". Below that I have a script tag with some embedded code that depends on the result of the previous 2 scripts.
Is there a way to make sure that this code only gets executed once the first 2 scripts have finished?

<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>

CodePudding user response:

Make your inline script a module one and import the required resources from there:

<script type="module">
  import result1 from "./src/js/script1.js";
  import result2 from "./src/js/script2.js";
  console.log('Hello SO');
</script>

Live example Source

CodePudding user response:

You can make use of the onl oad callback of scripts to make sure the order is maintained.

let scriptsLoaded = 0;

//script1
var script1 = document.createElement('script');
script.type = 'module';
script.src ='./src/js/script1.js';
document.head.appendChild(script);

//script2
var script2 = document.createElement('script');
script.type = 'module';
script.src ='./src/js/script2.js';
document.head.appendChild(script);

script1.onLoad = function () {
    scriptsLoaded  ;
    if(scriptsLoaded == 2) //load third script
}

script2.onLoad = function () {
    scriptsLoaded  ;
    if(scriptsLoaded == 2) //load third script
}

CodePudding user response:

<script> tags with type="module" are automatically given a defer attribute (see load and execute order of scripts), so to make the third tag run after, it also needs to be deferred. Since this isn't possible with inline scripts (as mentioned in the comments), you can either move the script to another file and reference it with the src attribute or wrap the code in a event listener for the DOMContentLoaded event (see https://stackoverflow.com/a/41395202/19461620)

Using an external script file:

<script type="text/javascript" src="./script.js" defer></script>

script.js

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

Using a DOMContentLoaded callback:

<script type="text/javascript" >
    window.addEventListener('DOMContentLoaded', function() {
        (function($) {
            //do something with b-lazy plugin, lightbox plugin and then with flexslider
        })(jQuery);
    });
</script>
  • Related