alex / alex/what-happens-when

Not particularly comprehensive and cannot reflect the comprehensive level of a developer

未关闭
#341 0 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
没有语言数据
星标
43.3k
派生
5.7k
PR 合并指标
30 天内没有已合并 PR

描述

I wrote an article before, you can use google translate into English to view, there is a more detailed introduction
[Process from entering URL to page load](https://github.com/wuhaohao1234/http-protocol)
# Process from entering URL to page loading

> Improve your front-end knowledge system by one question

## content

1. Receive the url from the browser to open the network request thread (the mechanism of the browser and the relationship between the process and the thread)

2. Open the network thread to issue a complete http request (dns query, tcp/ip request, five-layer Internet protocol)

3. Receive a request from the server to receiving the request in the corresponding background (load balancing, security interception and internal background: query database, server-side rendering or client-side rendering)

4. HTTP interaction between background and foreground (http header, response code, message structure, cookie, common tools such as swagger)

5. http cache

6. The parsing process after the browser receives the http packet (dom tree rendering, render tree, reflow (also called rearrangement) or redraw, GPU drawing, external link resources (css, img, js, font, video, docs) ))

7. CSS visual format (element rendering rules, such as containing block, control box, BFC, IFC and other concepts)

8. JS engine parsing process (JS interpretation stage, preprocessing stage, execution stage to generate execution context, VO, scope chain, recycling mechanism, etc.)

9. Others (different knowledge modules can be expanded, such as cross-domain, web security, hybrid mode, etc.)

## 1. Receive the url from the browser to open the network request thread

### 1. Multi-process browser

A program (such as qq) can have multiple processes, and a process can have multiple threads to do different things

The browser is multi-process, there is a master process, and each tab page will open a new process (in some cases, multiple tabs will merge processes).

Processes may include master processes, plug-in processes, GPUs, tab pages (browser kernels), and more.

* Browser process: the main process of the browser (responsible for coordination, master control), there is only one

- Responsible for browser interface display and user interaction. such as forward, backward, etc.
- Responsible for the management of each page, creating and destroying other processes
- Draw the Bitmap in memory obtained by the Renderer process to the user interface
- Management of network resources, downloading, etc.

* Third-party plug-in process: each type of plug-in corresponds to a process, which is only created when the plug-in is used (such as the vue process in chrome)

* GPU process: at most one, for 3D drawing

* Browser rendering process (kernel): By default, one process per tab page, independent of each other, controls page rendering, script execution, event processing, etc. (sometimes optimized, such as multiple blank tabs will be merged into one process)

#### 1.1. Advantages of browser multi-process (the disadvantage is that it occupies memory)

* Avoid a single page crash affecting the entire browser
* Avoid third-party plugin crashes affecting the entire browser
* Multi-process take full advantage of multi-core
* It is convenient to use the sandbox model to isolate processes such as plug-ins and improve browser stability

### 2. Multi-threaded browser kernel

Each tab page can be regarded as a browser kernel process, and then this process is multi-threaded, and it has several types of sub-threads:

* GUI rendering thread

- Responsible for rendering browser interface, parsing HTML, CSS, building DOM tree and RenderObject tree, layout and drawing, etc.
- When the interface needs to be repainted (Repaint) or caused by some operation to cause reflow (reflow, also called reflow), this thread will execute
- Note that the GUI rendering thread and the JS engine thread are mutually exclusive. When the JS engine executes, the GUI thread will be suspended (equivalent to being frozen), and GUI updates will be saved in a queue until the JS engine is idle. implement.

* JS engine thread (this is also the reason why the js engine is single-threaded)
- Also known as JS kernel, responsible for processing Javascript scripts. (eg V8 engine)
- The JS engine thread is responsible for parsing Javascript scripts and running the code.
- The JS engine has been waiting for the arrival of the tasks in the task queue, and then processing them. There is only one JS thread running the JS program in a Tab page (renderer process) at any time.
- Also note that the GUI rendering thread and the JS engine thread are mutually exclusive, so if the JS execution time is too long, the rendering of the page will be incoherent, resulting in the blocking of page rendering and loading.
* Event trigger thread (this is also the reason for synchronization and asynchrony in the browser)

- It belongs to the browser instead of the JS engine and is used to control the event loop (it is understandable that the JS engine is too busy by itself, and the browser needs to open another thread to assist)
- When the JS engine executes code blocks such as setTimeOut (also from other threads in the browser kernel, such as mouse clicks, AJAX asynchronous requests, etc.), the corresponding tasks will be added to the event thread
- When the corresponding event meets the triggering conditions and is triggered, the thread will add the event to the end of the pending queue and wait for the JS engine to process it
- Note that due to the single-threaded relationship of JS, the events in these pending queues have to be queued for processing by the JS engine (only executed when the JS engine is idle)

* Timer thread

- The thread where the legendary setInterval and setTimeout are located
- The browser timing counter is not counted by the JavaScript engine (because the JavaScript engine is single-threaded, if it is in a blocked thread state, it will affect the accuracy of the timing)
- Therefore, timing and triggering are performed by a separate thread (after the timing is completed, it is added to the event queue and executed after waiting for the JS engine to be idle)
- Note that the W3C stipulates in the HTML standard that the time interval below 4ms in setTimeout is required to be counted as 4ms.

* Asynchronous http request thread

- After XMLHttpRequest is connected, a new thread request is opened through the browser
- When a state change is detected, if a callback function is set, the asynchronous thread will generate a state change event and put the callback into the event queue. And then executed by the JavaScript engine.

#### 2.1, the communication process between the Browser process and the browser kernel (Renderer process)

1. When the Browser process receives a user request, it first needs to obtain the page content (such as downloading resources through the network), and then pass the task to the Render process through the RendererHost interface

2. The Renderer interface of the Renderer process receives the message, and after a brief explanation, hand it over to the rendering thread, and then start rendering

* The rendering thread receives the request, loads the web page and renders the web page, which may require the Browser process to obtain resources and the GPU process to help rendering

* Of course there may be JS threads operating the DOM (this may cause reflow and redraw)

* Finally, the Render process passes the result to the Browser process

* Browser process receives the result and draws the result

#### 2.2, combing the relationship between threads in the browser kernel

##### 2.2.1, GUI rendering thread and JS engine thread are mutually exclusive

Since JavaScript can manipulate the DOM, if the interface is rendered while modifying these element attributes (that is, the JS thread and the UI thread run at the same time), the element data obtained before and after the rendering thread may be inconsistent

Therefore, in order to prevent unpredictable rendering results, the browser sets the GUI rendering thread and the JS engine to be mutually exclusive. When the JS engine executes, the GUI thread will be suspended.

GUI updates are kept in a queue and executed as soon as the JS engine thread is idle.

###### 2.2.2, JS blocks page loading

Assuming that the JS engine is performing a huge amount of calculations, even if the GUI is updated at this time, it will be saved in the queue and executed after the JS engine is idle.
Then, due to the huge amount of calculation, the JS engine is likely to be idle for a long time, and it will naturally feel that the huge card is incomparable.

###### 2.2.3, WebWorker, JS multithreading

Web Workers provide an easy way for web content to run scripts in a background thread. Threads can perform tasks without interfering with the user interface

A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file

This file contains code that will run in worker threads; workers run in another global context, different from the current window

So using the window shortcut to get the scope of the current global (instead of self) inside a Worker will return an error

1. When creating a Worker, the JS engine applies to the browser to open a child thread (the child thread is opened by the browser, completely controlled by the main thread, and cannot operate the DOM)

2. The JS engine thread and the worker thread communicate in a specific way (postMessage API, you need to serialize the object to interact with the thread specific data)

If there is very time-consuming work, please open a separate Worker thread, so that no matter how earth-shaking it is, it will not affect the main thread of the JS engine.
Only after the result is calculated, communicate the result to the main thread

###### 2.2.4, WebWorker and SharedWorker

Essentially the difference between a process and a thread. SharedWorker is managed by an independent process, WebWorker is just a thread under the render process

1. WebWorker only belongs to a certain page and will not be shared with the Render process (browser kernel process) of other pages

* So Chrome creates a new thread in the Render process (each Tab page is a render process) to run the JavaScript program in the Worker.

2. Shared Worker is shared by all pages of the browser and cannot be implemented in the same way as Worker, because it is not affiliated with a Render process and can be shared by multiple Render processes
* So the Chrome browser creates a separate process for SharedWorker to run JavaScript programs, and there is only one SharedWorker process for each same JavaScript in the browser, no matter how many times it is created.

##### 2.2.5 Browser rendering process

1. The browser enters the url, the main process of the browser takes over, and a download thread is opened.
Then make an http request (omitting DNS query, IP addressing, etc.), then wait for the response, get the content,
Then transfer the content to the Renderer process through the RendererHost interface

2. The browser rendering process begins

After the browser kernel gets the content, rendering can be roughly divided into the following steps:

1. Parse html to build dom tree

2. Parse CSS to build a render tree (parse CSS code into a tree-shaped data structure, and then combine it with DOM into a render tree)

3. Layout render tree (Layout/reflow), responsible for the calculation of the size and position of each element

4. Draw the render tree (paint) and draw the page pixel information

5. The browser will send the information of each layer to the GPU, and the GPU will composite each layer and display it on the screen.

After the rendering is completed, the load event is processed, and then it is processed by its own JS logic.

###### 2.2.6, the sequence of load event and DOMContentLoaded event

1. When the DOMContentLoaded event is triggered, only when the DOM is loaded, excluding style sheets and images.

2. When the onload event is triggered, all the DOM, style sheets, scripts, and images on the page have been loaded.

Order DOMContentLoaded -> load

##### 2.2.7. Will CSS loading block DOM tree rendering?

1. CSS loading will not block DOM tree parsing (DOM is built as usual when loading asynchronously)

2. But it will block the rendering of the render tree (when rendering, you need to wait for the css to load, because the render tree needs css information)

##### 2.2.8, normal layers and composite layers

The composite concept is mentioned in the rendering step.

First of all, the normal document flow can be understood as a composite layer (here called the default composite layer, no matter how many elements are added, they are all in the same composite layer)

Second, absolute layout (fixed as well), although it can be separated from the normal document flow, it still belongs to the default composite layer.

Then, a new composite layer can be declared with hardware acceleration, which will allocate resources separately
(Of course, it will also be separated from the normal document flow, so that no matter what changes in this composite layer, it will not affect the reflow redraw in the default composite layer)

In the GPU, each composite layer is drawn separately, so it does not affect each other, which is why the hardware acceleration effect of some scenes is excellent

* How to turn into a composite layer (hardware accelerated)

1. The most common way: translate3d, translateZ

2. opacity property/transition animation (the composite layer will be created during the animation execution process, and the element will return to the previous state after the animation does not start or ends)

3. The will-chang attribute (this is relatively remote) is generally used in conjunction with opacity and translate (and has been tested, in addition to the above can
Except for properties that cause hardware acceleration, other properties will not become composite layers),

##### 2.2.9, the difference between absolute and hardware acceleration

Although absolute can be separated from the normal document flow, it cannot be separated from the default composite layer. Therefore, even if the information in the absolute changes without changing the render tree in the normal document flow,
However, when the browser finally draws, the entire composite layer is drawn, so changes in the information in the absolute will still affect the drawing of the entire composite layer.
(The browser will redraw it. If there is a lot of content in the composite layer, the drawing information brought by absolute changes too much, and the resource consumption is very serious)

And the hardware acceleration is directly in another composite layer (start from a new one), so its information change will not affect the default composite layer
(Of course, the interior will definitely affect its own composite layer), just trigger the final composition (output view)

##### 2.2.10, the role of composite layers

Generally, an element will become a composite layer after hardware acceleration is enabled, which can be independent of the ordinary document flow. After modification, the entire page can be avoided from redrawing and performance can be improved.

But try not to use a large number of composite layers, otherwise the page will become more stuck due to excessive resource consumption.

##### 2.2.11. Please use index for hardware acceleration

When using hardware acceleration, use index as much as possible to prevent the browser from creating composite layer rendering for subsequent elements by default

principle:

** In webkit CSS3, if this element has hardware acceleration and the index level is relatively low, then other elements behind this element (the level is higher than this element, or the same, and the relative or absolute attribute is the same), will be The default is composite layer rendering, if not handled properly, it will greatly affect performance**

##### 2.2.12 Talking about the running mechanism of JS from Event Loop

* JS is divided into synchronous tasks and asynchronous tasks

* Synchronization tasks are executed on the main thread, forming an execution stack

* In addition to the main thread, the event-triggered thread manages a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.

* Once all the synchronous tasks in the execution stack are executed (the JS engine is idle at this time), the system will read the task queue, add the runnable asynchronous tasks to the executable stack, and start execution.

###### 2.2.13, timer

Timer thread in the browser: When using setTimeout or setInterval, it requires the timer thread to time, and after the time is completed, a specific event is pushed into the event queue.

##### 2.2.14. There is a difference between using setTimeout to simulate regular timing and using setInterval directly.

Each time setTimeout is timed, it will be executed, and then setTimeout will continue after a period of execution, and there will be more errors in the middle (the error is related to the execution time of the code)

And setInterval pushes an event at a precise interval every time (however, the actual execution time of the event is not necessarily accurate, and it may be that the event has not been executed yet, and the next event will come)

setInterval has some fatal problems:

* The cumulative effect (mentioned above), if the setInterval code does not finish executing before (setInterval) is added to the queue again, it will cause the timer code to run several times in a row with no gaps in between.
Even if executed at normal intervals, the code execution time of multiple setIntervals may be shorter than expected (because the code execution takes a certain time)

* And when the browser is minimized and displayed, setInterval is not not executing the program, it will put the callback function of setInterval in the queue, and when the browser window is opened again, it will be executed in an instant. Therefore, in view of so many but The problem, the best solution is generally considered to be: use setTimeout to simulate setInterval, or use requestAnimationFrame directly on special occasions

##### 2.2.15. Advanced event loop: macrotask and microtask (macrotask and microtask)
There is a new concept in Promise in es6: microtask

* macrotask (also known as macro task), it can be understood that the code executed each time the execution stack is a macro task (including each time an event callback is obtained from the event queue and placed on the execution stack for execution)
- Each task will execute the task from beginning to end, and will not execute other tasks
- In order to enable the orderly execution of JS internal tasks and DOM tasks, the browser will re-render the page after the execution of a task and before the execution of the next task starts.
* microtask (also known as microtask), which can be understood as a task that is executed immediately after the current task execution ends

- That is, after the current task task, before the next task, before rendering
- So its response speed will be faster than setTimeout (setTimeout is task), because there is no need to wait for rendering
- That is, after a macrotask is executed, all microtasks generated during its execution will be executed (before rendering)
* macrotask: main code block, setTimeout, setInterval, etc. (as you can see, each event in the event queue is a macrotask)

* microtask: Promise, process.nextTick, etc.

* In the node environment, the priority of process.nextTick is higher than Promise__, which can be simply understood as: after the macro task ends, the nextTickQueue part of the micro task queue will be executed first, and then the Promise part of the micro task will be executed.

**Understanding of threads**

* Events in macrotask are placed in an event queue, and this queue is maintained by the event triggering thread

* All microtasks in microtask are added to the microtask queue (Job Queues), waiting for the execution of the current macrotask to complete, and this queue is maintained by the JS engine thread

**Execution mechanism**

- Execute a macro task (get it from the event queue if it is not on the stack)
- If a microtask is encountered during execution, it will be added to the task queue of the microtask
- After the macro task is executed, all micro tasks in the current micro task queue are executed immediately (executed in sequence)
- After the current macro task is executed, start to check the rendering, and then the GUI thread takes over the rendering
- After rendering, the JS thread continues to take over and starts the next macro task (obtained from the event queue)

**The difference between Promise's polyfill and the official version:**

* In the official version, it is the standard microtask form
* polyfill, generally simulated by setTimeout, so it is in the form of macrotask

### 3. Parse url

A URL generally includes several parts:

* protocol, protocol header, such as http, https, ftp, etc.

* host, host domain name or IP address

* port, port number

*path, directory path

* query, the query parameter

* fragment, the hash value after #, is generally used to locate a certain location

### 4. Network requests are all separate threads

A separate thread needs to be opened for each network request. For example, if the URL is resolved to the http protocol, a new network thread will be created to process the resource download.

Therefore, the browser will open a network thread according to the parsed protocol to request resources (here, it is temporarily understood that it is developed by the browser kernel, if there is an error, it will be repaired later).

## Second, open the network thread to issue a complete http request

### 2.1, DNS query to get IP

If the input is a domain name, it needs to be resolved into IP by dns. The general process is as follows:

* If the browser has a cache, use the browser cache directly, otherwise use the local cache, if not, use the host

* If there is no local, query the dns domain name server (of course, there may be routes in the middle, there are caches, etc.), and the corresponding IP is queried

**The domain name query may go through the CDN scheduler (if there is a CDN storage function). **

For example: https://www.jsdelivr.com/, there are many resource mirrors of github and npm on this website

You need to know that dns parsing is time-consuming, so if you parse too many domain names, the loading of the first screen will become too slow, you can consider dns-prefetch optimization.

### 2.3, tcp/ip request

The essence of http is tcp/ip request.

Need to understand the 3-way handshake rule to establish a connection and four waves when disconnecting.

TCP divides HTTP long messages into short messages, and establishes a connection with the server through a three-way handshake for reliable transmission.

### 2.4, three-way handshake steps to establish a connection

* Client: hello, are you the server?

* Server: hello, I am server, are you client?

* Client: yes, I am client

### 2.5, four wave steps to disconnect

* Active party: I have closed the active channel to you, and can only receive passively

* Passive side: Receive the information that the channel is closed

* Passive party: Then I will also tell you that my active channel to you is also closed.

* Active party: The data is finally received, after which the two parties cannot communicate

### 2.6, tcp/ip concurrency limit

* Browsers have restrictions on concurrent tcp connections under the same domain name (ranging from 2 to 10).

* And in http1.0, a resource download often needs to correspond to a tcp/ip request.

* So for this bottleneck, there are many resource optimization schemes.

### 2.7, the difference between get and post

* Although both get and post are essentially tcp/ip, they are not only at the http level, but also different at the tcp/ip level.

* get will generate one tcp packet and post two.

specific

* When a get request is made, the browser will send the headers and data together, and the server responds with 200 (return data)

* When a post request is made, the browser sends the headers first, the server responds with 100continue, the browser sends the data, and the server responds with 200 (return data).

The difference here is at the specification level, not the implementation.

### 2.8, five-layer Internet protocol stack

General concept: From the client's HTTP request to the server's reception, there will be a series of processes in the middle.

From the application layer sending http request, to the transport layer establishing a tcp/ip connection through three-way handshake, then to the ip addressing of the network layer, then to the encapsulation and framing of the data link layer, and finally to the physical layer for transmission using the physical medium.

### 2.8, five-layer Intel protocol stack

1. Application layer (dns, http) DNS resolves to IP and sends http request
2. The transport layer (tcp, udp) establishes a tcp connection (three-way handshake)
3. Network layer (IP, ARP) IP addressing
4. Data Link Layer (PPP) encapsulation into framing
5. Physical layer (using physical media to transmit bit streams) Physical transmission (and then through twisted pairs, electromagnetic waves and other media during transmission)

Of course, there is actually a complete seven-layer OSI framework. Compared with this, there are more session layers and presentation layers.

* Presentation layer: mainly deals with the representation of exchanged information in two communication systems, including data format exchange, data encryption and decryption, data compression and terminal type conversion, etc.

* Session layer: It specifically manages the dialogue between different users and processes, such as controlling the login and logout process

## 3. Receive the request from the server to the corresponding background receiving the request

### 3.1 Load Balancing

For large-scale projects, due to the large amount of concurrent access, one server is often overwhelmed, so there are usually several servers to form a cluster, and then cooperate with the reverse proxy to achieve load balancing.

The requests initiated by the user all point to the scheduling server (reverse proxy server, such as installing nginx to control load balancing), and then the scheduling server allocates different requests to the servers in the corresponding cluster according to the actual scheduling algorithm for execution, and then the scheduler waits for the actual server. the HTTP response and feed it back to the user.

### 3.2 Background processing

Generally, the background is deployed into the container (for example: docker), so it is generally:

* First, the container receives the request (such as the tomcat container)

* Then the background program in the corresponding container receives the request (such as a java program)

* Then there will be its own unified processing in the background, and the response result will be responded to after processing

generalize

1. Generally, some backends have unified verification, such as security interception (some belong to the front end, in terms of forms), cross-domain verification (here refers to cors, set through request.header)

2. If this step does not conform to the rules, the corresponding http message is directly returned (such as rejecting the request, etc.)

3. Then when the verification is passed, it will enter the actual background code. At this time, the program receives the request and then executes it (such as querying the database, a large number of calculations, etc.)

4. After the program is executed, it will return an http response packet (generally, this step will also be multi-layered encapsulation)

5. Then the package is sent from the backend to the frontend to complete the interaction

## Fourth, the http interaction between the background and the foreground (common tools such as swagger)
When the front-end and the back-end interact, the http message is used as the information carrier. So http is a very important piece of content, and this part focuses on it.

### 4.1, http message structure

The message generally includes: general header, request/response header, request/response body.

#### 4.1.1, general header

1. Request Url: The requested web server address

2. Request Method: Request method (Get, POST, OPTIONS, PUT, HEAD, DELETE, CONNECT, TRACE)

3. Status Code: The return status code of the request, such as 200 for success, 304 for cache

4. Remote Address: The requested remote server address (will be converted to IP)

In the case of cross-domain rejection, it may be that the method is options, the status code is 404/405, etc. (of course, there are actually many possible combinations).

Among them, Method words are generally divided into two batches:

* HTTP1.0 defines three request methods: GET, POST and HEAD methods.
2. HTTP1.1 added five new request methods: OPTIONS, PUT, DELETE, TRACE and CONNECT methods.

The most commonly used is the status code, which is often judged by the status code.

* 200 - Indicates that the request was successfully completed and the requested resource was sent back to the client

* 304 - The requested web page has not been modified since the last request, please use the local cache on the client side

* 400 - The client request is wrong (for example, it can be intercepted by the security module)

* 401 - Request Unauthorized

* 403 - Forbidden access (for example, it can be prohibited when not logged in)

* 404 - resource not found

* 500 - internal server error

* 503 - Service unavailable

Meaning of roughly different range states

* 1xx——Indication information, indicating that the request has been received, continue processing

* 2xx - success, indicating that the request has been successfully received, understood, and accepted

* 3xx - redirection, further action must be taken to complete the request

* 4xx - client error, the request has a syntax error or the request cannot be fulfilled

* 5xx - server-side error, the server failed to fulfill a legitimate request

3. Request/Response Headers

- Accept: The receiving type, indicating the MIME type supported by the browser (the Content-Type returned by the benchmarking server)

- Accept-Encoding: The compression type supported by the browser, such as gzip, etc., cannot be accepted beyond the type

- Content-Type: the type of entity content sent by the client

- Cache-Control: Specify the caching mechanism followed by requests and responses, such as no-cache

- If-Modified-Since: Last-Modified corresponding to the server, used to match to see if the file has changed, it can only be accurate to within 1s, in http1.0

- Expires: cache control, no request is made during this time, cache is used directly, http1.0, and it is server time

- Max-age: represents how many seconds the resource is cached locally. It will not be requested within the valid time, but will be cached. In http1.1

- If-None-Match: ETag corresponding to the server, used to match whether the content of the file has changed (very accurate), in http1.1

- Cookie: there is a cookie and it will be automatically brought when accessing from the same domain

- Connection: How to handle long connections when the browser communicates with the server, such as keep-alive

- Host: The requested server URL

- Origin: Where did the original request originate from (only accurate to the port), Origin respects privacy more than Referer

- Referer: The source URL of the page (applicable to all types of requests, it will be accurate to the detailed page address, this field is commonly used in csrf interception)

- User-Agent: some necessary information of the user client, such as UA header, etc.

4. Commonly used response headers (parts)

* Access-Control-Allow-Headers: Server-side allowed request headers

* Access-Control-Allow-Methods: server-side allowed request methods

* Access-Control-Allow-Origin: The request origin header allowed by the server (for example, *)

* Content-Type: The type of entity content returned by the server

* Date: The time the data was sent from the server

* Cache-Control: tell browsers or other clients what environment is safe to cache documents

* Last-Modified: The last modification time of the requested resource

* Expires: When should the document be considered expired and thus not be cached anymore

* Max-age: How many seconds should the client's local resources be cached, valid after Cache-Control is enabled

* ETag: The current value of the entity tag of the request variable

* Set-Cookie: Set the cookie associated with the page, the server passes the cookie to the client through this header

* Keep-Alive: If the client has keep-alive, the server will also respond (such as timeout=38)

* Server: some information about the server

In general, request headers and response headers are matched and analyzed.

For example, the Accept in the request header must match the Content-Type in the response header, otherwise an error will be reported.

For example, when making a cross-domain request, the Origin in the request header must match the Access-Control-Allow-Origin in the response header, otherwise a cross-domain error will be reported.

For example, when caching is used, If-Modified-Since and If-None-Match in the request header correspond to Last-Modified and ETag in the response header respectively.

#### 4.2 Request/Response Entities

When an HTTP request is made, in addition to the header, there is also a message entity. Generally speaking, some required parameters are put into the request entity (for post request). For example, the serialized form of parameters (a=1&b=2) can be placed in the entity, or the form object can be placed directly (FormData object, which can be mixed with parameters and files when uploading), and so on.

The general response entity is to put the content that the server needs to pass to the client. Generally, in the current interface request, the entity is the json format of the information, and like a page request, an html string is directly placed in it, and then the browser parses and renders it by itself.

#### 4.3CRLF

CRLF (Carriage-Return Line-Feed), which means carriage return and line feed, generally exists as a separator.

There is a CRLF separation between the request header and the entity message, and a CRLF separation between the response header and the response entity.

Separator category:

* CRLF->Windows-style

* LF->Unix Style

* CR->Mac Style

#### 4.4 cookies and optimization

A cookie is a local storage method of the browser. It is generally used to help the client communicate with the server. It is often used for identity verification and is used in conjunction with the session of the server. (The cookie is not safe, the user can see it, generally we let the cookie have an expiration time)

##### 4.4.1 Application Scenario

* On the login page, the user has logged in

* At this point, the server will generate a session, which contains information about the user (such as username, password, etc.)

* Then there will be a sessionid (equivalent to the key corresponding to the session on the server)

* Then the server writes a cookie in the login page, the value is: jsessionid=xxx

* Then the browser has this cookie locally. When visiting the page under the same domain name in the future, it will automatically bring the cookie and automatically check it, and there is no need to log in again within the valid time.

Generally speaking, cookies are *not allowed to store sensitive information* (do not store user names and passwords in plain text), because it is very insecure. If you must forcibly store them, first of all, you must set httponly in the cookie (this way you cannot Through js operation), you can also consider asymmetric encryption such as rsa (because in fact, the browser is also easy to be conquered locally, and it is not safe).

In addition, since the browser will bring the local cookie by default when requesting resources of the same domain name, it needs to be optimized in some scenarios.

For example the following scenario:

* The client has a cookie under the domain name A (this can be written by the server when logging in)

* Then there is a page under domain name A, and the page has many dependent static resources (all of domain name A, for example, there are 20 static resources)

* There is a problem at this point, when the page loads and requests these static resources, the browser will bring cookies by default

* In other words, each of these 20 HTTP requests for static resources must bring a cookie, but in fact static resources do not require cookie verification

* This wastes cookies and reduces access speed

Solution:

* Group static resources and put them under different subdomains

* When the subdomain is requested, it will not bring the cookie of the parent domain, so it avoids waste

* On the mobile side, if the number of domain names requested is too many, the request speed will be reduced (because the whole set of domain name resolution process is very time-consuming, and the general bandwidth of the mobile terminal is not as good as that of the PC, now it is 5g faster, and the mobile terminal network speed generally better)

* At this point, you need to use an optimization solution: dns-prefetch (allow the browser to resolve the dns domain name in advance when it is idle, but please use it reasonably and do not abuse it)

### 4.5, gzip compression

Gzip is a compression format that requires browser support to be effective (but generally supported by browsers now), and gzip compression efficiency is very good (up to about 70%). Then gzip is generally opened by web servers such as apache and tomcat.

In addition to gzip, the server will also have other compression formats (such as deflate, which is not as efficient as gzip, and is not popular), so generally you only need to enable gzip compression on the server, and then subsequent requests are based on the gzip compression format. Very convenient.

### 4.6, long connection and short connection

* Long connection: A tcp/ip connection can send multiple data packets continuously. During the tcp connection holding period, if no data packets are sent, both parties need to send detection packets to maintain the connection. Generally, you need to do online maintenance by yourself (similar to heartbeats) Bag)

* Short connection: When there is data exchange between the two parties, a tcp connection is established. After the data transmission is completed, the tcp connection is disconnected.

Then at the http level:

* In http1.0, a short connection is used by default, that is to say, the browser establishes a connection without performing an http operation, and terminates the connection when the task ends. For example, each static resource request is a separate connection.

* Since http1.1, a long connection is used by default. When using a long connection, there will be this line Connection:keep-alive. In the case of a long connection, when a web page is opened, the client and the server are used to transmit http. The tcp connection will not be closed. If the client visits the server's page again, it will continue to use this established connection.

Note: *keep-alive will not be maintained forever, it has a duration, which is generally configured in the server (such as apache), and the long connection will only be effective when both the client and the server support it. *

### 4.7, http 2.0

http2.0 is not https, it is equivalent to the next-generation specification of http (for example, the request of https can be of the http2.0 specification). Then briefly describe the significant differences between http2.0 and http1.1:

* In http1.1, every time a resource is requested, a tcp/ip connection needs to be opened, so the corresponding result is that each resource corresponds to a tcp/ip request. Since tcp/ip itself has a concurrency limit, when When there are more resources, the speed slows down significantly

* In http2.0, one tcp/ip request can request multiple resources, that is to say, as long as one tcp/ip request, several resources can be requested and divided into smaller frame requests, and the speed is significantly improved.

If http2.0 is fully applied, many optimization schemes in http1.1 do not need to be used (such as packaging into sprites, splitting static resources with multiple domain names, etc.).

Some features of http2.0:

* Multiplexing (ie a tcp/ip connection can request multiple resources)

* Header compression (http header compression, reducing size)

* Binary framing (a binary framing layer is added between the application layer and the transport layer to improve transmission performance and achieve low latency and high throughput)

* Server-side push (the server can send multiple responses to a request from the client, and can actively notify the client)

* Seek priority (if the stream is given a priority, it will be processed based on this priority, and it is up to the server to decide how many resources are needed to process the request.)

### 4.8, https:

https is the secure version of http. For example, some payments and other operations are basically based on https, because the safety factor of http requests is too low.

In simple terms, https and http
The difference is: **Before the request, an ssl link will be established to ensure that the next communication is encrypted and cannot be easily intercepted and analyzed**

Generally speaking, if you want to upgrade a website to https, you need back-end support (the back-end needs to apply for a certificate, etc.), and then the overhead of https is also larger than that of http (because additional secure links and encryption are required), so generally speaking The experience of http2.0 with https is better (because http2.0 is faster)

Generally speaking, the main concern is the SSL/TLS handshake process, as follows (briefly):

1. The browser requests to establish an SSL connection and sends a random number to the server – Client random and an encryption method supported by the client, such as RSA encryption, which is transmitted in plaintext at this time.

2. The server selects a set of encryption algorithms and Hash algorithms, replies with a random number – Server random, and sends its own identity information back to the browser in the form of a certificate (the certificate contains the website address, which is encrypted asymmetrically. public key, and information such as the certificate authority)

3. After the browser receives the certificate from the server

* Verify the legitimacy of the certificate (whether the issuing authority is legal, whether the URL contained in the certificate is the same as the one you are visiting), if the certificate is trusted, the browser will display a small lock, otherwise there will be a prompt

* After the user receives the certificate (whether it is trusted or not), the browsing will generate a new random number – Premaster secret, and then the public key in the certificate and the specified encryption method encrypt the Premastersecret and send it to the server.

* Use Client random, Server random and Premaster secret to generate a symmetric encryption key-session key for HTTP link data transmission through a certain algorithm

* Calculate the handshake message using the agreed HASH algorithm, encrypt the message with the generated session key, and finally send all the previously generated information to the server.

4. The server receives the reply from the browser

* Use known encryption and decryption methods to decrypt with your own private key to obtain Premastersecret
* The same rules as the browser generate the session key
* Use the session key to decrypt the handshake message sent by the browser, and verify whether the Hash is consistent with the one sent by the browser
* Use the session key to encrypt a handshake message and send it to the browser

5. The browser decrypts and calculates the HASH of the handshake message. If it is consistent with the HASH sent by the server, the handshake process ends.

After that, all https communication data will be encrypted by the session key generated by the previous browser and using the symmetric encryption algorithm.

## Five, http cache

In the front-end and back-end HTTP interaction, the use of cache can greatly improve the efficiency, and basically all front-end projects that have performance requirements must use cache.

### 5.1 Strong cache and weak cache

The cache can be simply divided into two types: strong cache (200fromcache) and negotiated cache (304).

* In the case of strong cache (200fromcache), if the browser determines that the local cache has not expired, it will be used directly without making an http request

* When negotiating the cache (304), the browser will initiate an http request to the server, and then the server will tell the browser that the file has not changed, and let the browser use the local cache

For negotiated caches, use Ctrl+F5 to force a refresh to invalidate the cache. But for a strong cache, when it has not expired, the resource path must be updated to initiate a new request (changing the path is equivalent to another resource, which is also a commonly used technique in front-end engineering).

### 5.2 Cache header brief description

* Strong cache control
````
(http1.1) Cache-Control/Max-Age
(http1.0) Pragma/Expires
````
* Negotiate cache control
````
(http1.1) Cache-Control/E-tag
(http1.0) Pragma/Last-Modified
````
There is also a meta tag in the HTML page that controls the caching scheme - Pragma.
``

### 5.3 The difference of the head

First of all, it is clear that the development of http is from http1.0 to http1.1, and in http1.1, there are some new contents to make up for the shortcomings of http1.0.

Cache control in http1.0:

* Pragma: Strictly speaking, it does not belong to the special cache control header, but when it sets no-cache, it can invalidate the local strong cache (belongs to compilation control to implement specific instructions, mainly because it is compatible with http1.0, so has been widely used in the past)

* Expires: Configured by the server, it belongs to a strong cache, which is used to control that the browser will not send a request before the specified time, but directly use the local cache. Note that Expires generally corresponds to the server-side time, such as Expires: Fri,30Oct199814 :19:41

* If-Modified-Since/Last-Modified: These two appear in pairs and belong to the content of the negotiated cache. The header of the browser is If-Modified-Since, and the server is Last-Modified. Its role Yes, when the request is initiated, if If-Modified-Since and Last-Modified match, it means that the server resource has not changed, so the server will not return the resource entity, but only return the header, notifying the browser that the local cache can be used . Last-Modified, as the name suggests, refers to the last modification time of the file, and it can only be accurate to within 1s

Cache control in http1.1:

* Cache-Control: Cache control header, with no-cache, max-age and other values

* Max-Age: Configured by the server to control the strong cache. Within the specified time, the browser does not need to send a request, but directly uses the local cache. Note that Max-Age is the value of the Cache-Control header, not an independent The header, such as Cache-Control:max-age=3600, and it is worth the absolute time, calculated by the browser itself

* If-None-Match/E-tag: These two appear in pairs and belong to the content of the negotiation cache. The header of the browser is If-None-Match, and the server is E-tag. Similarly, send After the request, if the If-None-Match matches the E-tag, it means that the content has not changed, and the browser is notified to use the local cache. Unlike Last-Modified, the E-tag is more accurate. It is similar to a fingerprint, based on FileEtagINodeMtimeSize is generated, that is to say, as long as the file changes, the fingerprint will change, and there is no 1s accuracy limit.

### 5.4, Max-Age compared to Expires

Expires uses server-side time, but sometimes there is a situation where client-side time and server-side time are out of sync. In this way, there may be problems, causing the browser's local cache to be useless or unable to expire, so it is generally not recommended to use Expires after http1.1. However, Max-Age uses the calculation of the client's local time, so there is no such problem, so it is recommended to use Max-Age.

Note that if both Cache-Control and Expires are enabled, Cache-Control takes precedence.

### 5.5, E-tag compared to Last-Modified

Last-Modified:

* Indicates when the file on the server was last changed

* It has a defect that it can only be accurate to 1s,

* Then there is another problem that some files on the server will change periodically, resulting in cache invalidation

And the E-tag:

* is a fingerprint mechanism, representing file-related fingerprints

* Only the file changes will change, and as long as the file changes, it will change,

* There is no precise time limit, as long as the file is once, the E-tag will be different immediately

If it has both E-tag and Last-Modified, the server will check the E-tag first.

## Six, the process of parsing the page

### 6.1 html rendering, building dom tree

1. Conversion: The browser converts the obtained HTML content (Bytes) into a single character based on his encoding

2. Tokenizing word segmentation: The browser converts these characters into different token tokens according to the HTML specification standard. Each token has its own unique meaning and set of rules

3. Lexing lexical analysis: The result of word segmentation is to get a bunch of tokens, and then convert them into objects, which define their attributes and rules respectively

4. DOM construction: Because HTML tags define the relationship between different tags, this relationship is like a tree structure. For example: the parent node of the body object is the HTML object

### 6.2 css rules

Put the corresponding attribute styles on the dom tree

### 6.3 Construction of render tree

Once the DOM tree and CSSOM are in place, it's time to start building the render tree. In general, the render tree corresponds to the DOM tree, but not strictly one-to-one. Because some invisible DOM elements will not be inserted into the rendering tree, such as invisible tags such as head or display:none, etc.

### 6.4, rendering process

1. Calculate css style

2. Build the render tree

3. Layout, the main positioning coordinates and size, whether to wrap, various position overflow z-index properties

4. Draw, draw the image

Then, the DOM or CSS is dynamically modified through js, resulting in re-layout (Layout) or rendering (Repaint).

The conceptual difference between Layout and Repaint

* Layout, also known as Reflow, is reflow. Generally means that the content, structure, position or size of the element has changed, requiring recalculation of styles and rendering trees

* Repaint, that is, repaint. It means that the change of the element only affects some appearance of the element (for example, background color, border color, text color, etc.), at this time, you only need to apply the new style to draw the element.

The cost of reflow is higher than that of redrawing, and the reflow of a node often leads to the reflow of child nodes and peer nodes, so the optimization scheme generally includes it, and try to avoid reflow.

### 6.5. What will cause reflow

1. Page rendering initialization

2. DOM structure changes, such as deleting a node

3. Render tree changes, such as reducing padding

4. Window resize

5. Get some properties (width, height) and cause reflow.

Many browsers will optimize the reflow and will do a batch reflow when the number is sufficient, but in addition to the direct change of the render tree, when some attributes are obtained, the browser will also trigger the reflow in order to obtain the correct value, which makes the browser Optimization doesn't work

1. offset (Top/Left/Width/Height)

2. scroll(Top/Left/Width/Height)

3. cilent(Top/Left/Width/Height)

4. width, height

5. Called getComputedStyle() or IE's currentStyle

Reflow must be accompanied by repaint, but repaint can occur alone.

1. Reduce the change of style item by item, it is better to change the style at one time, or define the style as a class and update it at one time

2. Avoid looping DOM, create a documentFragment or div, apply all DOM operations on it, and finally add it to window.document (the DOM in memory that is not displayed on the page or added to the body, are called virtual dom)

3. Avoid reading attributes such as offset multiple times. can't be avoided then cache them in a variable

4. Absolutely or fixedly position the complex element so that it is out of the document flow, otherwise the reflow cost will be very high

**Changing font size will cause reflow**

### 6.6 Simple and composite layers

The above rendering stops at drawing, but in fact, the drawing step is not so simple. It can be combined with the concept of composite layer and simple layer. It is not expanded here, but briefly introduced:

* It can be considered that there is only one composite layer by default, and all DOM nodes are under this composite layer

* If hardware acceleration is enabled (translate3d, transform), you can turn a node into a composite layer

* The drawing between composite layers does not interfere with each other and is directly controlled by the GPU

* In a simple layer, even if it is an absolute and other layouts, the change does not affect the overall reflow, but because in the same layer, it will still affect the drawing, so the performance is still very low when doing animation. The composite layer is independent, so it is generally recommended to use hardware acceleration for animation.

### 6.7 Download of external links of resources

1. Handling when encountering external links

When encountering css, js, img external links, a separate download thread will be opened to download resources (in http1.1, each resource download must open an http request, corresponding to a tcp/ip link)
.

2. Encounter CSS style resources

* CSS is downloaded asynchronously and will not block the browser to build the DOM tree

* But it will block rendering, that is, when building the render, it will wait until the css download and parsing is completed (this is related to browser optimization, which prevents the css rules from changing constantly and avoids repeated construction)

* With the exception, CSS declared by the media query will not block rendering

3. js resources

* Blocks the browser's parsing, that is to say, when an external script is found, it needs to wait for the script to download and execute before continuing to parse the HTML (as mentioned above, the GUI rendering thread and the JS engine thread are mutually exclusive, when JS When the engine is executing, the GUI thread will be suspended (equivalent to being frozen), and GUI updates will be stored in a queue and executed immediately when the JS engine is idle)

* Browser optimization, generally modern browsers are optimized. When the script is blocked, it will continue to download other resources (of course there is a concurrency limit), but although the script can be downloaded in parallel, the parsing process is still blocked, which means that this must be done. The next parsing will take place after the script is executed. Parallel download is just an optimization.

* defer and async, ordinary scripts will block browser parsing, but you can add defer or async attributes, so the script becomes asynchronous, you can wait until the parsing is completed before executing *defer is delayed execution, and async is asynchronous implement*

* async is executed asynchronously. It will be executed after the asynchronous download is completed. The execution order is not guaranteed. It must be before onload, but it is not sure before or after the DOMContentLoaded event.

* defer is delayed execution, which looks like the effect of putting the script behind the body in the browser (although it should be before the DOMContentLoaded event according to the specification, but in fact, the optimization effect of different browsers is different, and it may be in it later)

4. img

Asynchronous loading, no blocking

## Seven, CSS visual format model

* CSS specifies that each element has its own box model (equivalent to specifying how this element is displayed)

* Then the visual format model is to place these boxes on the page according to the rules, that is, how to layout

* In other words, the box model specifies how the boxes are placed on the page, how the boxes interact, etc.

**The visual format model of CSS is to specify how the browser handles the document tree in the page**

Keywords:

* Containing Block

* Controlling Box

* BFC (Block Formatting Context)

*IFC (Inline Formatting Context)

* Positioning system

* float

### 7.1 Containing Block

The positioning and size of an element's box will be related to a rectangular box, which is called a containing block. An element will create containing blocks for its descendant elements, however, it does not mean that an element's containing block is its parent element, an element's containing block is related to the styles of its ancestors, etc.

* The root element is the topmost element, it has no parent node, its containing block is the initial containing block

* Static and relative containing blocks are created from the content of its nearest block-level, cell, or inline-block ancestor

*fixed containing block is currently visible window

* An absolute containing block is created from its nearest ancestor whose position property is absolute, relative or fixed

* If its ancestor element is an inline element, the containing block depends on the direction property of its ancestor element

* If the ancestor element is not an inline element, then the area containing the block should be the ancestor element's padding boundary

### 7.2 Controlling Box

Concepts related to block-level elements and block boxes and inline elements and line boxes.

* Block-level elements will generate a block box (BlockBox), and the block box will occupy an entire line to contain sub-boxes and generated content

* The block box is also a block containing box (ContainingBox), which either only contains block boxes or only inline boxes (not mixed). If there are block-level elements and inline elements inside the block box, the inline elements will be anonymous block boxes. surrounded

### 7.3, BFC (Block Formatting Context)

FC is the format context, which defines the element rendering rules inside the box, which is relatively abstract, such as:

* FC is like a big box with many elements inside

* The box can separate the elements inside and the elements outside (so the outside does not affect the rendering inside the FC)

* Internal rules can be: how to position, calculate width and height, margin folding, etc.

Different types of boxes participate in different FC types. For example, block-level boxes correspond to BFC, and inline boxes correspond to IFC.

**It does not mean that all boxes will generate FC, but will only be generated when certain conditions are met, and the corresponding rendering rules will only be applied after the corresponding FC is generated. **

#### 7.4.1 BFC Rules:

In a block formatting context, the outer left edge of each element touches the left edge of the containing block (for right-to-left formatting, the outer right edge touches the right edge), even if there is a float (so a floated element normally sticks directly to its the left side of the containing block, which coincides with the normal element), unless this element also creates a new BFC.

* The inner boxes are placed vertically, one after the other

* The vertical direction of the box is determined by the margin, and the margins between two boxes belonging to the same BFC will overlap

* BFC area will not overlap with floatbox (can be used for typography)

* BFC is an isolated and independent container on the page, and the child elements inside the container will not affect the elements outside. vice versa

* When calculating the height of BFC, floating elements also participate in the calculation (no floating collapse)

#### 7.4.2 How to trigger BFC

1. The root element

2. The float property is not none

3. position is absolute or fixed

4. display is inline-block, flex, inline-flex, table, table-cell, table-caption

5. overflow is not visible

It is mentioned here that display:table itself does not generate BFC, but it generates an anonymous box (a box containing display:table-cell), and this anonymous box generates BFC.

#### 7.4.3IFC (Inline Formatting Context)

IFC is the formatting context generated by the inline box.

Floating elements may lie between the containing block edge and the line box edge, and although line boxes in the same inline formatting context usually have the same width (the width of the containing block), they may shorten the available width due to floating elements, And change in width.

Line boxes in the same inline formatting context usually have different heights (e.g., one line contains a tall graphic, while other lines contain only text), and when the sum of the widths of the inline boxes on a line is less than the width of the line boxes containing them, they are Alignment in the horizontal direction, depending on the text-align property. Empty inline boxes should be ignored.

That is, no text, whitespace reserved, inline elements with non-zero margin/padding/border, and other regular stream content (such as images, inline blocks and inline tables), and line boxes that do not end with a newline, must be Treated as a zero-height line box.

* Inline elements always apply IFC rendering rules

* Inline elements will be rendered using IFC rules, such as text-align can be used for centering

* Inside the block box, for anonymous elements such as text, an anonymous line box will be generated, and the IFC rendering rules will be applied inside the line box

* Inside the inline box, for those inline elements, the same IFC rendering rules apply

* In addition, inline-block will generate IFC on the outer layer of the element (so this element can be centered horizontally by text-align), of course, it will be rendered according to BFC rules inside

Compared with BFC rules, IFC may be more abstract (because there are not so well-organized rules and trigger conditions), but in general, it is the rendering rules of how the inline elements themselves are displayed and how they are placed in the box, described like this Should be easier to understand.

*IFC rules

In an inline formatting context, boxes are arranged horizontally one after the other, starting at the top of the containing block. Margin, border and padding in the horizontal direction are preserved between boxes, which can be aligned in different ways vertically: they are aligned at the top or bottom, or according to the baseline of the text within them.

#### 7.4.5 Line Box

The rectangular area containing those boxes, will form a row, called a row box. The width of the line box is determined by its containing block and the floating elements within it, and the height is determined by the rules for calculating the line height.

Rules for line boxes:

* If several inline boxes cannot fit into one inline box horizontally, they can be distributed among two or more vertically stacked inline boxes (i.e. the division of inline boxes)

* Line boxes stack without vertical splits and never overlap

* A row box is always high enough to accommodate all the boxes it contains. However, it may be higher than the tallest box it contains (eg box alignment causes baseline alignment)

* The left side of the line box touches the left side of its containing block, and the right side touches the right side of its containing block

## Eight, JS engine parsing process

### 8.1 Interpretation phase of JS

**JS is interpreted speech, so it doesn't need to be compiled ahead of time, it's run by the interpreter in real time**

The processing process of JS by the engine can be briefly described as follows:

1. Read the code, perform lexical analysis, and then decompose the code into tokens

2. Parsing the tokens and organizing the code into a syntax tree

3. Use the translator (translator) to convert the code to bytecode (bytecode)

4. Use a bytecode interpreter to convert bytecode to machine code

In the end, the computer executes the machine code. In order to improve the running speed, modern browsers generally use just-in-time compilation (JIT-JustInTimecompiler). That is, the bytecode is only compiled at runtime, whichever line is used, and the compilation result is cached (inlinecache), so that the running speed of the entire program can be significantly improved. Moreover, different browsers may have different policies. Some browsers omit the translation step of bytecode and directly convert to machine code (such as chrome's v8).

*The core JIT compiler compiles the source code into machine code to run*

### 8.2, JS preprocessing stage

The above will be the overall process of the interpreter. Here we will mention that there will be a preprocessing stage (such as variable promotion, semicolon completion, etc.) before the official execution of JS.

The preprocessing stage will do a few things to ensure that the JS can be executed correctly, here are just a few:

1. Semicolon completion

JS execution requires a semicolon, why not add a semicolon

The reason is that the JS interpreter has a Semicolon Insertion rule, which will add semicolons in appropriate positions according to certain rules.

* When there is a newline (including a multi-line comment containing a newline), and the next token cannot match the previous syntax, it will automatically complete the semicolon.

* When there is }, if a semicolon is missing, a semicolon will be added.

* At the end of the program source code, if a semicolon is missing, a semicolon will be added.

2. Variable promotion

It generally includes function hoisting and variable hoisting.

Since there is a lot of content here, if you say something, you have to talk about variable declarations, function declarations, formal parameters, the priority order of actual parameters, and let in es6

### 8.3, JS execution phase

After the interpreter interprets the grammar rules, it starts to execute, and then the entire execution process roughly includes the following concepts:

* Execution context, execution stack concepts (such as global context, currently active context)

* VO (variable object) and AO (active object)

* scope chain

* this mechanism

1. A brief explanation of the execution context

* JS has an execution context
* When the browser loads the script for the first time, it will create a global execution context and push it to the top of the execution stack (cannot be popped)
* Then every time you enter another scope, create the corresponding execution context and push it to the top of the execution stack
* Once the corresponding context is executed, pop it from the top of the stack and give control of the context to the current stack.
* This is executed in sequence (will eventually return to the global execution context)

If the program finishes execution, is popped off the execution stack, and is not referenced (no closure is formed), then the memory used in this function will be automatically reclaimed by the garbage processor.

Then execute context with VO. The relationship between the scope chain and this is that each execution context has three important properties:

* variable object

* scope chain

* this

2. VO and AO

VO is a property (abstract concept) of the execution context, but only the variable object of the global context is allowed to be accessed indirectly through the property name of the VO (because in the global context, the global object itself is the variable object).

AO (activationobject), when the function is activated by the caller, the AO is created.

* In function context: VO===AO

* in the global context: VO===
this===global

In general, VO will store some variable information (such as declared variables, functions, arguments parameters, etc.).

3. Scope chain

It is an attribute in the execution context, the principle is very similar to the prototype chain, and its role is very important.

In the function context, look for a variable foo, if found in the function's VO, use it directly, otherwise go to its parent scope chain (parent) to find it. If it is not found in the parent, continue to look up, and report an error until it is not found in the global context.

4. this pointer

*this is a property of the execution context, not a property of a variable object*

* this is not a process like searching for variables

* When this is used in the code, the value of this is obtained directly from the execution context without searching from the scope chain

* The value of this only depends on the context when entering the context

Summary: *this points to the caller and its environment*

### 8.4 Recycling mechanism

JS has a garbage processor, so there is no need to manually reclaim memory, it is handled automatically by the garbage processor. Generally, garbage processors have their own recycling policies. For example, for those functions that are executed, if there are no external references (which will form closures if they are referenced), they will be recycled. (Of course, the recovery action is generally cut into different time periods to prevent performance from being affected).

Common recycling rules:

* mark clear

* reference count

The basic GC scheme of the Javascript engine is (simple GC): markandsweep (mark and sweep), which is briefly explained as follows:

1. Iterate over all accessible objects.

2. Recycle objects that are no longer accessible.

*js advanced programming*
````
When a variable enters the environment, for example, a variable is declared in a function, the variable is marked as "entering the environment".
Logically, the memory occupied by variables entering an environment can never be freed, because they may be used as soon as execution flow enters the corresponding environment.
And when a variable leaves the environment, it is marked as "leaving the environment".
The garbage collector will mark all variables stored in memory when it runs (of course, any marking method can be used).
Then, it unmarks variables in the environment and variables referenced by variables in the environment (closures, that is, variables in the environment and related references are unmarked).
Variables marked after this will be treated as variables ready for deletion, because variables in the environment are no longer accessible.
Finally, the garbage collector completes the memory cleanup, destroying those marked values ​​and reclaiming the memory space they occupied.
````

#### 8.5 Reference counting

Track and record the number of times each value is referenced. When a value is referenced, the number of times is +1, and -1 when it is reduced. Next time, the garbage collector will reclaim the memory of the value with the number of times 0 (of course, it is easy to get circular references. bug).

### 9. Defects of GC

Like other languages, javascript's GC strategy cannot avoid a problem: during GC, it stops responding to other operations, which is for security reasons. The GC of Javascript is 100ms or more, which is good for general applications, but for JS games and applications that require high continuity of animation, it is troublesome.

*This is the point where the engine needs to be optimized: avoid long-term stoppage caused by GC*

### 10. GC optimization strategy

Here are the commonly used ones: Generation GC. The purpose is to distinguish between "temporary" and "persistent" objects by:

* Multi-recycle "temporary object" area (young generation)

* Less recycling of "persistent objects" area (tenured generation)

* Reduce the objects that need to be traversed each time, thereby reducing the time-consuming of each GC.

Like the node v8 engine, it uses generational recycling (like java, the author is the author of the java virtual machine.)

## Nine, other

### Cross-domain: browser's same-origin policy

Solutions to cross-domain solutions

* cors backend settings (mentioned above)

* jsonp

jsonp only supports get requests, the principle is to let the backend return a callback function through the src in the script

* Reverse proxy
### web security

Is ajax safe

### The concept of viewport viewport (mobile terminal)

## X. Reference Links

https://segmentfault.com/a/1190000012925872

https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/

https://coolshell.cn/articles/9666.html

http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/

http://blog.csdn.net/dojiangv/article/details/51794535

http://bbs.csdn.net/topics/340204423

https://segmentfault.com/a/1190000004246731

http://www.bubuko.com/infodetail-1379568.html

http://fex.baidu.com/blog/2014/05/what-happen/

http://www.cnblogs.com/winter-cn/archive/2013/05/21/3091127.html

https://fanerge.github.io/%E6%B5%8F%E8%A7%88%E5%99%A8%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90 %86-webkit%E5%86%85%E6%A0%B8%E7%A0%94%E7%A9%B6.html

http://www.cnblogs.com/TomXu/archive/2012/01/12/2308594.html

https://segmentfault.com/q/1010000000489803

贡献指南

这个仓库没有索引到贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。