0

Possible Duplicate:
Javascript Load Order

If we have a number of script tags in the header of the HTML page then is it necessary that they will be rendered in a serial fashion or can they reder in any order. To be more specific, I have script tags in head part of HTML and they are only meant for loading .js files. Now if a script tag comes earlier does it mean that it will be render earlier and no other .js file will be loaded until current file has been loaded. Also if we have two functions both with same name then by placing one of the functions in script tag (inline) ensures that only this function will get called when a call to this duplicate name function is made.

Thanks, Jack

Community
  • 1
  • 1
Jack Sparrow
  • 21
  • 1
  • 3
  • JavaScript files and code are loaded/executed in the order they are defined. Later function definitions will overwrite existing ones. – Felix Kling Oct 20 '11 at 13:07

2 Answers2

2

<script> tags in an HTML document are executed sequentially unless the async attribute is set. This is because they can modify the HTML document (including, for example, adding further scripts that must be loaded and executed before the next script in the original HTML document) via calls to document.write.

Since the order does not matter and you should not use document.write, but the DOM (or a library which uses the DOM), you should place your scripts at the bottom of the document. Although latter variable assignments (in JavaScript, that includes function definitions) overwrite the former, it is advisable to use a different prefix for functions so that the names do not collide, and/or use private variables, like this:

function f() {
  console.log("do one thing");
}

(function() {
  function f() {
    console.log("do another thing");
  }
  f(); // prints "another"
})();

// The "another" function is not visible here.
phihag
  • 278,196
  • 72
  • 453
  • 469
0

The order of loading java script is sequentially

If you use any cross domain script that will load after local script(Moving the script in same domain)

Try to place the script just before of the html otherwise the script will override the variables