Ben Ben - 7 months ago 12
Javascript Question

Load JavaScript depending on previously asynchronously loaded JavaScript

<script src="script1.js" async></script>
<script src="script2.js"></script>


script2.js
is depending on
script1.js
. Since
script1.js
isn't loaded completely when
script2.js
is executed, it doesn't work. How to fix this?

Edit: I cannot remove the
async
attribute and I can only modify the content of
script2.js
.

Answer

If your first script must be async, better also put the second as async.

A naive solution is to regularly check a global variable that the first script may be exporting.

Let's say script1 attaches script1export to window, you can do something like:

function onScript1Loaded(){
   // script 2 content
}

function waitForScript1(){
  if(window.script1export){
    onScript1Loaded();
  } else {
    getAnimationFrame(waitForScript1);
  }
}

waitForScript1();

It is not ideal, but it will work. If you are not in a hurry and would like the checks to be a little bite more spaced out so that you can save a bit of CPU ressources, use a setTimeout with the delay you want instead of an animation frame.