FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

Javascript - order of loading

 


dayveday
Just wondering, if I have more than one external script in my page (ie. two <script src=...>) is there any guaranteed run order for them?

That is, can I be sure the first one mentioned will run before the second one mentioned? Or can it depend on which on is downloaded first (the second one could already be in a cache, for example)?

Cheers
MrBlueSky
External js-files are always included and executed in your pages in the order in which you specifiy them. The browser actually stops rendering and loading the page while downloading an external javascript file.

Quote:

A <script> tag with the src attribute specified behaves exactly as if the contents of the specified JavaScript file appeared directly between the <script> and </script> tags.


Quote:

JavaScript statements that appear between <script> and </script> tags are executed in the order that they appear in the script. When a file has more than one script, the scripts are executed in the order in which they appear (with the exception of scripts with the defer attribute, which IE executes out of order). The JavaScript code in <script> tags is executed as part of the document loading and parsing process.

Any <script> element that does not have a defer attribute may call the document.write( ) method (described in detail in Chapter 15). The text passed to this method is inserted into the document at the location of the scripts. When the script is finished executing, the HTML parser resumes parsing the document, starting with any text output by the script.



"Javascript, the definitive Guide", David Flanagan, O'Reilly
dayveday
Thanks for that - it certainly makes my life easier!
MrBlueSky
Later I thought: theory from books is all nice and all, but let's test it..

Write 2 scripts:

slow.php
Code:

<?php
   
   sleep(7);
   
?>

alert("I am slow");

(Waits 7 seconds and then returns a line of javascript)

fast.js
Code:

alert("I am fast");


and then load this html-page in your browser:
Code:

<HTML>
<BODY>
   <script src='slow.php'></script>
   <script src='fast.js'></script>

    <SCRIPT type="text/javascript">
      alert("I am in the Document itself");
    </SCRIPT>
</BODY>
</HTML>


And indeed. The scripts are run in order of appearance, even though the second javascript include can be loaded very quicker than the first one.
Reply to topic    Frihost Forum Index -> Scripting -> Html, CSS and Javascript

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.