8

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>
Chris
  • 647
  • 1
  • 8
  • 32
  • 1
    Put the one in front of the other. Have you tried it? Has there been a problem? – epascarello Jul 20 '16 at 12:38
  • 2
    Well this is already the case so what is your issue??? Scripts are loaded synchronously by default – A. Wolff Jul 20 '16 at 12:39
  • the JS file which is first will be executed first. is your script2 executing before completion of first file? – Sahith Vibudhi Jul 20 '16 at 12:39
  • 1
    You're asking us this question after you've tried something? Did it worked? If not, why? Is there an ACTUAL problem or you're asking that "for fun"? – Alon Eitan Jul 20 '16 at 12:41
  • check this : [http://stackoverflow.com/questions/34574910/how-to-load-2-javascript-files-async-and-run-one-after-another](http://stackoverflow.com/questions/34574910/how-to-load-2-javascript-files-async-and-run-one-after-another) – Vaibhav Jul 20 '16 at 12:42
  • 2
    Remember that HTML is rendered top-bottom, so what you have in your code already guarantees that `script1.js` will fire before `script2.js`. – Drew Kennedy Jul 20 '16 at 12:48
  • Yes sorry, my first script calls a php function to retrieve an api key for a web map, which is then used as part of the second script. I am finding that when I first load the page, it isn't displaying my map, but on a refresh it works fine. I just wanted to find out whether it could be an issue with how my javascript files are arranged. – Chris Jul 20 '16 at 13:09
  • 1
    "my first script calls a php function" and this call is async so there you have the source of your problem – Roland Starke Jul 20 '16 at 13:20
  • @RolandStarke what is the best way to all this to run before the rest of my javascript executes? – Chris Jul 20 '16 at 15:24
  • Your question itselfs an answer :D – Dilip Oganiya Jul 21 '17 at 07:08

8 Answers8

14

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.

Ehsan
  • 12,655
  • 3
  • 25
  • 44
3

<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

Alireza
  • 100,211
  • 27
  • 269
  • 172
0

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>');
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • as `#first` is already loaded the time you attatch the event listener i don't think this will work. – Roland Starke Jul 20 '16 at 12:43
  • DOwsn't loading start after DOM ready? And then the script should be kicks in before loading is finished. Otherwise appen first script by js too ... – eisbehr Jul 20 '16 at 12:45
0

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.

Mario Santini
  • 2,905
  • 2
  • 20
  • 27
0

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:

Community
  • 1
  • 1
Rob Scott
  • 7,921
  • 5
  • 38
  • 63
  • 1
    Using that you don't have any garanty than first srcipt is loaded before second one. You are doing some async ajax calls here. The only garanty is that `$.getScript('script2.js');` is call after `$.getScript('script1.js');` but the first one can takes more time than second one to complete – A. Wolff Jul 20 '16 at 12:47
  • Isn't that what the OP stated? To "need to make sure that the first file, script1.js, is run before my second script, script2.js." – Rob Scott Jul 20 '16 at 12:53
  • 1
    But your answer just doesn't do it, $.getScript() is async. In fact, OP's posted code already has his expected behaviour. The opening question afterall doesn't really make sense – A. Wolff Jul 20 '16 at 12:58
0
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")
};
0

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>
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
0

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");
   });
});
mk23
  • 1,257
  • 1
  • 12
  • 25