mgPePe
mgPePe

Reputation: 5907

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/or variables.

I don't know which one will load first.

What is the proper way of doing it?

NOTE: one of the scripts (A) loads data asynchronously and the script (B) needs to wait till all the data is loaded and started before it can continue (ex youtube video is loaded from (A) and needs to start playing before (B) can execute)

Upvotes: 0

Views: 145

Answers (2)

davids
davids

Reputation: 6371

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.

Upvotes: 0

Sirko
Sirko

Reputation: 74036

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

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

Upvotes: 2

Related Questions