9

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>
10
  • 1
    Put the one in front of the other. Have you tried it? Has there been a problem? Commented Jul 20, 2016 at 12:38
  • 2
    Well this is already the case so what is your issue??? Scripts are loaded synchronously by default Commented Jul 20, 2016 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"? Commented Jul 20, 2016 at 12:41
  • 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. Commented Jul 20, 2016 at 12:48
  • 1
    "my first script calls a php function" and this call is async so there you have the source of your problem Commented Jul 20, 2016 at 13:20

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>');
});

2 Comments

as #first is already loaded the time you attatch the event listener i don't think this will work.
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 ...
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.

Comments

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:

3 Comments

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
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."
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
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")
};

Comments

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>

Comments

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");
   });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.