I have this index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="src/index.js"></script>
    <script>
      alert("2");
    </script>
  </head>
  <body>
  </body>
</html>

and this index.js:

alert("1");

How come alert('2') is apearing before alert('1').
As far as I know, loading src/index.js should be a blocking operation.

https://codesandbox.io/s/kww2o7rm0v

Thanks

2 Answers

-1
Codezters On

You could use the SetTimeout() function to make the second alert begin, or, call a function in the other script when the alert is exited, using:

alert("1");
// You could either put all of the other script in a function and call that here, or change the src of the script
document.GetElementById("ScriptID").src = "src/index.js";

Hope I could help!

-1
elena a On

Inserting a script element into the document can be accompanied by an onload callback function to ensure a sequential process. See Mozilla published docs under Web/API/HTMLScriptElement There are explanations and examples there.