Skip to content Skip to sidebar Skip to footer

How To Onload Two Javascript Files?

I have two different javascripts. I would like to start a function only after both of those js files or scripts have loaded, because they need to access each other's functions and/

Solution 1:

<script> are loaded synchronously in general. The evaluation of the document stops an waits until the script is loaded and executed. It is handled that way, because the script might interfere with the document by using something like document.write(), so the parser can not be sure, that the rest of the document stays the way it appears at that moment.

So to execute you scripts after they have loaded, just place a 3rd <script> tag holding the start-code behind those two, that are loading the scripts.

<scriptsrc="scriptA.js"></script><scriptsrc="scriptB.js"></script><script>// start something of scriptB
  scriptB.start();
</script>

Solution 2:

As scripts are loaded synchronously, just load the script that executes their functions after those two files. Anyway, if you have scripts with dependencies, I would encourage you to use a module loader, such as RequireJS. That way, you could define which modules/files should be loaded before the execution begins.

Post a Comment for "How To Onload Two Javascript Files?"