Chris Chris - 4 months ago 9
jQuery Question

Load an external javascript file before another?

I have two external javascript files within my html page.

I need to make sure that the first file, script1.js, is run before my second script, script2.js.

I have them within the body of my html page; how can I ensure that script2 is not used until the functions in script1 are run?

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>

<!-- Script 1 -->
<script src="js/script1.js"></script>

<!-- Script 2 -->
<script src="js/script2.js"></script>
</body>
</html>

Answer

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

So if your code is

<body>

    <!-- Script 1 -->
    <script src="js/script1.js"></script>

    <!-- Script 2 -->
    <script src="js/script2.js"></script>
</body>

Script 1 will be run before Script 2.