简体   繁体   中英

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

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_2 c 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM