Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does chrome understand compiled javascript?

Instead of having V8 compile JavaScript on the fly and then execute it, isn't it possible to just compile the JavaScript beforehand and then embed the machine code in the page instead of embedding JavaScript in the page?

like image 517
Hello Avatar asked Apr 22 '15 18:04

Hello


People also ask

Does Chrome compile or interpret JavaScript?

In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it.

Does Chrome understand typescript?

No, chrome does not support typescript natively - you compile it first to javascript, then you can run it in chrome (and any other browser). That is the main idea behind typescript - and I wouldn't expect browsers to support typescript directly in the near future (if ever).

How does JavaScript work under the hood?

It all starts with getting JavaScript code from the network. V8 parses the source code and turns it into an Abstract Syntax Tree (AST). Based on that AST, the Ignition interpreter can start to do its thing and produce bytecode. At that point, the engine starts running the code and collecting type feedback.

How does JavaScript code execute 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.


1 Answers

There are two main problems with shipping machine code on the web:

  1. Portability. No server can afford providing appropriate machine code for all possible system architectures out there (present and future). E.g., V8 already supports 10 different CPU architectures.
  2. Security. No client can afford to run random machine code on their machine without knowing if it can be trusted.

To address (1) you'd generally need to cross-compile machine code, which is more difficult and costly than compiling down from a high-level language. To address (2), you'd need to validate the machine code you receive, which is more difficult and costly than compiling a high-level language.

Machine code also tends to be much larger than high-level code, so there is a bandwidth issue as well.

Now, JavaScript may not be a particularly great choice of high-level language. But it is what we are stuck with as the language of the web.

like image 196
Andreas Rossberg Avatar answered Oct 06 '22 00:10

Andreas Rossberg