当前位置:网站首页>Go deep into the working principle of browser and JS engine (V8 engine as an example)

Go deep into the working principle of browser and JS engine (V8 engine as an example)

2022-06-25 05:00:00 MomentYY

How browsers work and JS engine

1. How browsers work

Enter the search content in the browser , How the browser loads pages ? as well as JavaScript How the code is executed in the browser ?

The general process can be seen in the following figure :

  • First , The user enters the server address in the browser search bar , Establish a connection with the server ;
  • The server returns the corresponding static resource ( It's usually index.html);
  • then , The browser gets index.html And then parse it ;
  • Encountered while parsing css or js file , Request from the server and download the corresponding css Document and js file ;
  • Last , The browser renders the page , perform js Code ;

 Insert picture description here

Then enter the server address , What happens when you hit the "return" button ?

  • The address entered by the browser DNS analysis , Resolve the domain name to the corresponding IP Address ;
  • And then to this IP The address to send http request , The server received the sent http request , Handle and respond to ;
  • Finally, the browser gets the content of the browser response ;

2. Browser kernel

The files downloaded by the browser from the server will eventually be parsed , So who is inside to help with parsing ? This involves the browser kernel . Different browsers are made up of different kernels , Here are a few common browser kernels :

  • Gecko: Early by Netscape and Mozilla Firefox Browser used ;
  • Trident: Developed by Microsoft ,IE Browsers have been using , but Edge The browser kernel has turned Blink;
  • Webkit: Apple is based on KHTML Development , And it's open source , be used for Safari,Google Chrome Browsers were also used in the early days ;
  • Blink:Google be based on Webkit Developed , yes Webkit A branch of , Currently used in Google Chrome、Edge、Opera wait ;

in fact , The browser kernel refers to the browser Layout engine (layout engine), Also known as browser engine 、 Page rendering engine or template engine .

3. Rendering in the browser

After the browser downloads the file from the server , You need to parse and render it , The process is as follows :

  • HTML Parser take HTML The analysis transforms into DOM Trees ;
  • CSS Parser Convert stylesheet parsing to CSS The rule tree ;
  • Conversion completed DOM Trees and CSS The rule tree Attachment( additional ) together , And generate a Render Tree( Render tree );
  • It should be noted that , It's generating Render Tree It will not be drawn immediately , There will be one in the middle Layout( Layout ) operation , That is to say Layout engine ;
  • Why do I need to use the layout engine again Render Tree To operate ? Because the state of the browser is different at different times ( For example, browser width ),Layout The function of is to determine the specific display position and display effect of elements ;
  • With the final Render Tree, The browser will Painting( draw ), The last part Display Exhibition ;
  • You can find another purple one in the picture DOM Triangle , Actually, this is js Yes DOM Related operations of ;
  • stay HTML When parsing , If you encounter JavaScript label , Will stop parsing HTML, Instead of loading and executing JavaScript Code ;

 Insert picture description here

that ,JavaScript Who will execute the code ? Here's the JavaScript engine Appearance. .

4.JavaScript engine

First of all, let's have a look at two questions JavaScript engine .

(1) Why JavaScript engine ?

  • First , We need to know JavaScript It's a high-level programming language , All high-level programming languages need to be translated into final machine instructions to execute ;
  • And we know that JS The code can be Node perform , The bottom layer is finally handed over to CPU perform ;
  • however CPU Only know your own instruction set , It's machine language , and JavaScript The main function of the engine is to help us JavaScript Code translation CPU Can understand the instructions , Was eventually CPU perform ;

(2)JavaScript What are the engines ?

  • SpiderMonkey: The first paragraph JavaScript engine , from Brendan Eich Development (JavaScript author );
  • Chakra: be used for IE browser , Developed by Microsoft ;
  • JavaScriptCore:Webkit The built-in JavaScript engine , Developed by apple ;
  • V8: The most powerful and popular at present JavaScript engine , from Google Development ;

5. Browser kernel and JS Engine relationship

Here we use Webkit Kernel as an example .

  • actually ,Webkit It's made up of two parts :

    • WebCore: be responsible for HTML analysis 、 Layout 、 Rendering and other related operations ;
    • JavaScriptCore(JSCore): Parsing and execution JavaScript Code ;
  • Written in a small program JavaScript The code is made up of JSCore Executive , That is, the engine used by the applet is JavaScriptCore:

    • Render layer : from Webview To parse and render wxml、wxss etc. ;

    • Logic layer : from JSCore To parse and execute JS Code ;

    • The following is the official architecture of the applet :

       Insert picture description here

6.V8 engine

Let's take a closer look at the powerful V8 engine .

6.1.V8 How the engine works

First, let's learn about the official response to V8 The definition of engine :

  • V8 Engine USES C++ Compiling Google Open source, high performance JavaScript and WebAssembly engine , It is used for Chrome and Node.js etc. , Can run independently , It can also be embedded in any C++ In the ..

  • So V8 Not just for JavaScript Of , It can also be used for WebAssembly( A binary instruction format for stack based virtual machines ), And you can Running on multiple platforms .

  • The following figure simply shows V8 The underlying architecture of :

     Insert picture description here

6.2.V8 The architecture of the engine

V8 There are three core modules in the underlying architecture of (Parse、Ignition and TurboFan), Next, the above architecture diagram will be described in detail .

(1)Parse modular : take JavaScript Code to AST( Abstract syntax tree ).

  • This process is mainly for JavaScript Source code Lexical analysis and Syntax analysis ;

  • Lexical analysis : Parse every word or symbol in the code , Eventually a lot of tokens( An array , It contains many objects );

    • such as , Yes const name = 'curry' This line of code performs lexical analysis :

      //  First of all, const To analyze , because const For a keyword , So the type will be recorded as a keyword , The value is const
      tokens: [
        {
               type: 'keyword', value: 'const' }
      ]
      
      //  Then on name To analyze , because name Is an identifier , So the type will be recorded as an identifier , The value is name
      tokens: [
        {
               type: 'keyword', value: 'const' },
        {
               type: 'identifier', value: 'name' }
      ]
      
      //  And so on ...
      
  • Syntax analysis : On the basis of lexical analysis , Get tokens Objects in the , According to their different types, we can further analyze the specific syntax , The resulting AST;

  • The above is a simple JS Lexical analysis and grammar analysis process introduction , If you want to check our JavaScript The code is passing Parse Converted AST, have access to AST Explorer Tools :

     Insert picture description here

  • AST There are many front-end application scenarios , For example, will TypeScript The code to JavaScript Code 、ES6 turn ES5、 And something like that. vue Medium template etc. , All of them are converted into corresponding AST, Then generate the object code ;

  • Refer to official documentation :https://v8.dev/blog/scanner

(2)Ignition modular : GoF Interpreter , Can be AST convert to ByteCode( Bytecode ).

  • Bytecode (Byte-code): It's a program that includes execution , By a sequence op Code / Binary file composed of data pairs , It's a kind of middle code .
  • take JS The code to AST It is convenient for the engine to operate it , It was said that JS The code is eventually converted into machine code for CPU Executive , Why do you have to convert to bytecode first ?
    • because JS The operating environment is not necessarily , May be windows or Linux or iOS, Different operating systems have CPU The machine instructions that can be recognized are also different . Bytecode is an intermediate code , It has cross platform features , then V8 The engine then compiles the bytecode into the corresponding machine instructions according to the current environment CPU perform .
  • Refer to official documentation :https://v8.dev/blog/ignition-interpreter

(3)TurboFan modular : A compiler , You can compile bytecode into CPU Know the machine code .

  • In understanding TurboFan Before the module, you can consider a problem , If every time the code is executed , You have to AST To bytecode and then to machine instructions , Is there a loss of performance ? Powerful V8 I've thought about it for a long time , So it's here TurboFan Such a library ;
  • TurboFan Can be obtained Ignition Some information collected , If a function is called multiple times in the code , Then it will be marked as Hot spot function , And then pass by TurboFan Convert to optimized machine code , When the function is executed again, the machine code is directly executed , Improve code execution performance ;
  • There is also a Deoptimization The process , In fact, that is The machine code is restored to ByteCode, such as , During the subsequent code execution, the parameter type passed into the hotspot function changes ( If sum Function is introduced to number Parameters of type , So it's adding ; If sum Function is introduced to String Parameters of type , That is to do string splicing ), The optimized machine code may not meet the requirements , It will be reversed to bytecode , Bytecode is compiled into correct machine code for execution ;
  • You can see from here that , If you pass a fixed type parameter to a function when writing code , It can optimize the execution efficiency of our code to a certain extent , therefore TypeScript compiled JavaScript The performance of the code is relatively good ;
  • Refer to official documentation :https://v8.dev/blog/turbofan-jit

6.3.V8 Engine execution process

V8 The official of the engine is Parse The process provides the following picture , Finally, let's take a closer look at Parse Specific implementation process .

  • ①Blink The kernel will JS Source code to V8 engine ;
  • ②Stream Get JS Source code for Encoding conversion ;
  • ③Scanner Conduct lexical analysis , Convert the code to tokens;
  • ④ After parsing ,tokens Will be converted into AST, In the middle of it will pass Parser and PreParser The process :
    • Parser: Direct analytical , take tokens Turn into AST Trees ;
    • PreParser: Pre parse ( Why do I need pre parsing ?)
      • Because not all of them JavaScript Code , It will be executed at the beginning , If one brain is right for all JavaScript Code parsing , It's bound to affect performance , therefore V8 And that's what happened Lazy Parsing( Delay parsing ) programme , Pre parsing unnecessary function code , That is, first parse the code content that needs to be executed , For functions Total analysis When the function is called .
  • ⑤ Generate AST after , Will be Ignition Convert to bytecode , Then turn it into machine code , Finally, the code execution process ;

 Insert picture description here

原网站

版权声明
本文为[MomentYY]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210529040056.html