Chris
Chris

Reputation: 677

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>

Upvotes: 9

Views: 18559

Answers (8)

mk23
mk23

Reputation: 1403

You can use jquery and try something like below reference - https://api.jquery.com/jquery.getscript/

$.getScript("js/script1.js", function() {
  console.log("script 1 loaded");
  $.getScript("js/script2.js",  function() {
      console.log("script 2 loaded");
   });
});

Upvotes: 0

Ehsan
Ehsan

Reputation: 12969

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.

Upvotes: 14

Alireza
Alireza

Reputation: 104910

<script> tag manage it for you... but read on...

JavaScript is synchronous, that means things it will executed line by line by default...

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

<head>
</head>

<body>

    <!-- Script 1 -->
    <script src="js/script1.js"></script> <!-- first gets executed and get finished -->

    <!-- Script 2 -->
    <script src="js/script2.js"></script> <!-- then second gets executed and get finished -->
</body>
</html>

But at the same JavaScript could be asynchronous too...

So there is an attribute for <script> tag which make the loading asynchronous... async attribute on script tag...

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

<head>
</head>

<body>

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

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

Definition and Usage


The async attribute is a boolean attribute.

When present, it specifies that the script will be executed asynchronously as soon as it is available.

Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

Upvotes: 3

sangram parmar
sangram parmar

Reputation: 8736

Your first script add new function .

function firstScriptFunction(){
 //i have done nothing here
}

Your Html page

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

<head>
</head>

<body>

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

    <!-- Script to load script 2 -- >
    <script type="text/javascript">

       function loadSecondScript() {
            if (!(typeof firstScriptFunction == 'function')) {
                window.setTimeout(loadSecondScript, 3000);
            }
            else {
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = 'js/script2.js';
                document.getElementsByTagName('body')[0].appendChild(script);

            }
        }
        $(document).ready(function(){
          loadSecondScript();
       });
    </script>

</body>
</html>

Upvotes: 0

sankaranarayanan
sankaranarayanan

Reputation: 1

function loadJS(file) {
    // DOM: Create the script element
    var jsElm = document.createElement("script");
    // set the type attribute
    jsElm.type = "application/javascript";
    // make the script element load file
    jsElm.src = file;
    // finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
}



myScript.src = 'http://code.jquery.com/jquery-2.1.4.min.js';
myScript.onload = function() { 
  loadJS("js/script2.js")
};

Upvotes: 0

Rob Scott
Rob Scott

Reputation: 8049

I understand that you're using javascript, but if you have jQuery, you can use (2) document.ready functions like so, and load those script files. Each document.ready will queue (using deferred) for each one.

$(function() {  // same as document.ready
     $.getScript('script1.js');
});

$(function() {
     $.getScript('script2.js');
});

Taken from:

Upvotes: 0

Mario Santini
Mario Santini

Reputation: 3013

Te ensure you load all your scripts in the proper way, you have to use some dependency handling library, like RequireJS, that allow you to execute the code just when your declared dependencies are loaded properly.

If you prefer, you could do it by yourself using something like jQuery.getScript, or do it in all javascript take that as an example.

Upvotes: 0

eisbehr
eisbehr

Reputation: 12452

You can't check if it was running. You could only watch the loading with jQuery and append the second script whenever it's finisished.

HTML:

<script id="first" src="js/script1.js"></script>

JS:

$("#first").on("load", function() {
    $("head").append('<script src="js/script2.js"></script>');
});

Upvotes: 0

Related Questions