1

if i have multiple javascript file on a page, will it always load serially across browser?

<script src='test1.js'></script>
<script src='test2.js'></script>
<script src='test3.js'></script>

for example, if the test*.js would write 1,2 and 3 using console.log, would it always write 1,2,3 on every browser?

if it isn't, is there a way to make it synchronous/serially?

dsolimano
  • 8,870
  • 3
  • 48
  • 63
Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • 1
    i believe yes, although I can't point you to any source. But it wouldn't make sense if it won't be loaded serially, because what if test2.js had code that depended on test1.js. it would error if doesn't load in order. – kennypu Feb 25 '13 at 09:10
  • 1
    You can have a look at http://headjs.com/ – Chetter Hummin Feb 25 '13 at 09:11
  • 1
    possible duplicate of [HTML parse order / script execution order](http://stackoverflow.com/questions/7052310/html-parse-order-script-execution-order) – JJJ Feb 25 '13 at 09:11
  • 1
    They will probably not load in serial order, but will be executed in order – bart s Feb 25 '13 at 09:12
  • 1
    possible duplicate of [Does inline javascript block the UI thread?](http://stackoverflow.com/questions/12545653/does-inline-javascript-block-the-ui-thread) – Fabrício Matté Feb 25 '13 at 09:27
  • 1
    Well, the above refers to UI thread, but it is obvious that any non-deferred non-async script will block rendering of the main thread including the execution of other scripts. – Fabrício Matté Feb 25 '13 at 09:34
  • 1
    @Kiswono Prayogo: Normally recent browsers make 5 to 6 parallel requests at a time. So your download will be parallel but the execution order will always be serial. – karthick Feb 25 '13 at 09:39

2 Answers2

2

I actually tested your example in the following browsers, each loaded serially:

  • Firefox
  • IE 7-9
  • Chrome
  • Opera
  • Safari

Please read this exhaustive answer for more information on why.

Community
  • 1
  • 1
ShadowScripter
  • 7,314
  • 4
  • 36
  • 54
1

for example, if the test*.js would write 1,2 and 3 using console.log, would it always write 1,2,3 on every browser?

Yes it would.

Browsers may load scripts in parallel, but will always execute them in order. An exception is when you have an async or defer attribute set on the script tag. Scripts dynamically created (through JS) are also async in nature.

Beware that placing too many scripts in your page may slow down rendering. If the server takes too long to serve one of the files as the markup below the script won't be rendered until the script has loaded and executed. It is good practice to minify all your JS files into a single one for production environment and use more script tags with good reason (e.g. using a CDN-hosted library).

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166