Question not for solution, Question to understand the system better
Experts! I know whenever you feed javascript code into javascript engine, It will execute by javascript engine immediately. Since, I haven't seen Engine's source code, I have few of questions as follows,
Let us assume I am loading couple of files from remote server namely FILE_1.js and FILE_2.js. And the code in FILE_2.js is requiring some of the code in FILE_1.js. So I have included files as follows,
<script type="text/javascript" src="FILE_1.js" ></script>
<script type="text/javascript" src="FILE_2.js" ></script>
So hopefully, I have done what Javascript Engine requires. Here unfortunately I have written 5000KB of code in FILE_1.js, and however I have 5KB of code in FILE_2.js. Since server is multi-threaded definitely FILE_2.js will be loaded into my browser before FILE_1.js completed.
How javascript engine handle this?
And If moved the code from FILE_2.js to inline-script tag as follows, what are actions taken by javascript engine to manage this dependency?
<script type="text/javascript" src="FILE_1.js" ></script>
<script type="text/javascript" >
// Dependent code goes here
</script>
Note: I am not expecting single word answer Single Threaded. I just want to know deep who is manage issuing request either browser or javascript engine or common guy? if the request/response is handled by common guy, then how javascript engine aware about this?
When I post an answer about the behavior of code, I always like to go to two places:
The specification:
The DOM API explicitly specifies scripts must be executed in order:
From 4.1 Scripting. Please check the list of exceptions to this rule before - having the
defer
orasync
attribute. This is specified well in 4.12.1.15.This makes sense, imagine:
It is generally better to use a module loader (that will defer script insertion and execution, and will manage dependencies correctly for you).
At the moment, the best approach is to use something like Browserify or RequireJS . In the future, we'll be able to use ECMAScript 6 modules.
The implementation:
Well, you mentioned it and I couldn't resist. So, if we check the Chromium blink source (still similar in WebKit):
Great, so we can see in the source code that it adds them in order parsed - just like the specification says.
Let's see how a script runner does:
And, using a timer, it fires them one by one when ready (or immediately, if nothing is pending):