Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Javascript is getting executed in browser by Javascript Engine?

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?

like image 205
HILARUDEEN S ALLAUDEEN Avatar asked Feb 28 '14 20:02

HILARUDEEN S ALLAUDEEN


People also ask

How is JavaScript executed in browser?

The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it.

How is JavaScript loaded in browser?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

How does the JavaScript engine work?

How does the JavaScript engine work? The JavaScript engine works on the JavaScript source code and puts it and then executes the compilation to binary instructions (machine code) that are easily understandable by the CPU.

Is JavaScript programs are executed by the script engine?

JavaScript is the dominant client-side scripting language of the Web, with 98% of all websites (mid–2022) using it for this purpose. Scripts are embedded in or included from HTML documents and interact with the DOM. All major web browsers have a built-in JavaScript engine that executes the code on the user's device.


1 Answers

When I post an answer about the behavior of code, I always like to go to two places:

  1. The specification
  2. The implementation

The specification:

The DOM API explicitly specifies scripts must be executed in order:

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

From 4.1 Scripting. Please check the list of exceptions to this rule before - having the defer or async attribute. This is specified well in 4.12.1.15.

This makes sense, imagine:

 //FILE_1.js
     var trololo = "Unicorn";
     ....
     // 1 million lines later
     trololo = "unicorn";
     var message = "Hello World";
//FILE_2.js
     alert(message); // if file 1 doesn't execute first, this throws a reference error.

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):

bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, 
                                    LegacyTypeSupport supportLegacyTypes)
    {
    .....
    } else if (client->hasSourceAttribute() && // has src attribute
              !client->asyncAttributeValue() &&// and no `async` or `defer`
              !m_forceAsync                    // and it was not otherwise forced                                   
              ) { // - woah, this is just like the spec
   m_willExecuteInOrder = true; // tell it to execute in order
   contextDocument->scriptRunner()->queueScriptForExecution(this, 
                                                            m_resource,
                                      ScriptRunner::IN_ORDER_EXECUTION);

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:

void ScriptRunner::queueScriptForExecution(ScriptLoader* scriptLoader,
                                          ResourcePtr<ScriptResource> resource,
                                          ExecutionType executionType){
     .....
     // Adds it in the order of execution, as we can see, this just 
     // adds it to a queue
     case IN_ORDER_EXECUTION:
        m_scriptsToExecuteInOrder.append(PendingScript(element, resource.get()));
        break;
     }

And, using a timer, it fires them one by one when ready (or immediately, if nothing is pending):

 void ScriptRunner::timerFired(Timer<ScriptRunner>* timer)
 {
 ...
    scripts.swap(m_scriptsToExecuteSoon);
    for (size_t i = 0; i < size; ++i) {
    ....
        //fire!
        toScriptLoaderIfPossible(element.get())->execute(resource);
        m_document->decrementLoadEventDelayCount();
    }
like image 147
Benjamin Gruenbaum Avatar answered Sep 17 '22 17:09

Benjamin Gruenbaum