In JavaScript is script guarantied to run after previous scripts in a document finished to run

StackOverflow https://stackoverflow.com/questions/21461497

  •  05-10-2022
  •  | 
  •  

Please consider the following snippet:

<!DOCTYPE html>
<html>
<head>
    <script src="script_1.js"></script>
    <script src="script_2.js"></script>
</head>
<body>
    <script>
        //script_3
    </script>
</body>
</html>

Can a one be sure that script_3 is run only after script_1 and script_2 finished to execute and script_2c is run only after script_1 finished, provided that there are no async code in script_1 and script_2?

Because now I have a situation, where script_3 from time to time starts before script_2 finished and it seems that all of the scripts don't have any async code. But I cannot reproduce this situation in a simpler example.

Thank you.

有帮助吗?

解决方案

Can a one be sure that script_3 is run only after script_1 and script_2 finished to execute and script_2c is run only after script_1 finished, provided that there are no async code in script_1 and script_2?

Yes, provided that none of the script tags uses the async or defer attributes.

Note that this is very different from this, however:

<script src="script1.js"></script>
<script src="script3.js"></script>

...where script1.js contains this:

var script = document.createElement('script');
script.src = "script2.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);

...in which case the order of script2.js vs. script3.js is chaotic.

However, if script1.js used document.write to output the script2.js script tag, that would be like the markup version, and the order would be assured (1, then 2, then 3).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top