0

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)

mgPePe
  • 5,677
  • 12
  • 52
  • 85

2 Answers2

2

<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>
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • One of them is a script that loads asynchronously data and more scripts from Youtube, so I have to wait till the whole video is loaded to start a function. – mgPePe Nov 20 '12 at 10:46
  • @mgPePe Then you probably have to add a function using `setInterval()` to check, whether the result is already present, because even the `onload` event of the script does not capture asynchronous parts of the script. – Sirko Nov 20 '12 at 10:57
  • So if I understand, B will go first, setting up variable `check = false` then also set interval to see if check continues to be false. A will load and with onload event will have `check = true` and that would trigger whatever I need, is that right? – mgPePe Nov 20 '12 at 11:07
  • @mgPePe No. You say, you have to wait until some youtube video has loaded, right? So load your script (just synchronous calls), then the other script (asynchronous calls) and have your function check, whether the new DOM elements of the video are present. If so, execute the rest of your code. – Sirko Nov 20 '12 at 11:09
  • @mgPePe maybe there is an option such as `async: false` for the functions that load stuff asynchronously? Maybe you should post some more code or provide a fiddle.. – nozzleman Nov 20 '12 at 11:10
0

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.

davids
  • 6,259
  • 3
  • 29
  • 50