preface

I am a small white, inspirational to do technology male god handsome force, currently living in Nanjing, do nearly 3 years front-end engineer, my second note.

References to this note and links to articles cited (thanks for sharing)

  • HTML, CSS, JS loading order
  • w3school
  • Order of JavaScript code execution
  • Render Tree construction process
  • Js redraw and rearrange DOM tree rendering optimization
  • JS stack
  • Talk about JS garbage collection
  • Start the network request thread until a complete HTTP request is issued
  • Senior front-end factory interview secrets, escort for you jin SAN Silver four, direct factory

Front knowledge

  1. Js stack concept
  2. Garbage collection mechanism
  3. Execution context -> Code is executed in a top-down order
  4. VO -> Variable Object, AO -> activation Object
  5. Scope and scope chain
  6. ! The DOCTYPE tag: declares the browser’s instructions about which VERSION of HTML the page should be written with. In HTML 4.01,
    declares a reference to DTD, because HTML 4.01 is based on SGML. DTDS dictate rules for markup languages so that browsers can render content correctly. HTML5 is not based on SGML, so there is no need to reference DTDS.
  7. HTML doesn’t start drawing until all the JS and CSS in the head have loaded, but HTML doesn’t wait for the js download at the end of the body to start drawing.
  8. Link loads CSS asynchronously and does not block loading

Js stack concept

Basic data types

  1. Undefined, Null, Boolean, String, Number and Symbol are stored in the stack directly according to their values. Each type of data occupies a fixed amount of memory space and is automatically allocated and released by the system

Reference data type

  1. Object, Array, Function and other data are stored in the heap memory, but the data pointer is stored in the stack memory, when we access the reference data, we first get the pointer from the stack memory, through the pointer to find the data in the heap memory

Garbage collection mechanism

The JavaScript engine has a background process called the garbage collector that monitors all objects and removes those that are not accessible.

// User has a reference to the object. // The object user is a reference data type."john"The heaplet user = {
  name: "John"}; // If the value of user is overwritten and the address is missing, it points to the store name:"john"There is no way to access it, no reference to it. The garbage collector discards John data and frees memory. user = nullCopy the code

Execution context (Execution environment)

When code is run, a corresponding execution environment is created, in which all variables are raised beforehand (variable promotion) and the code is executed from top to bottom, which is called the execution context.

  1. Single-threaded, running on the main process (one of the hallmarks of the JavaScript language is single-threaded)
  2. Synchronous execution, executed from top to bottom in sequence
  3. There is only one global context, which is ejected from the stack when the browser closes
  4. There is no limit to the number of execution contexts for a function
  5. Each time a function is called, a new execution context is created
  • It consists of three parts:

    • Variable Object (VO) – Active Object (AO)
    • Scope chain (lexical scope)
    • This points to the
  • Its type:

    • Global Execution Context (Global EC)
    • Function Execution Context (Callee)
    • Eval Execution context
  • Code execution process:

    • Creating a Global Context (Global EC)
    • The Global execution context (Global EC) executes line by line from top to bottom. When a function is encountered, the function execution context (Callee) is pushed to the top of the execution stack
    • The function execution context is activated as active EC, which starts executing the code in the function, and the caller is suspended
    • When the function completes, callee is removed from the stack by POP, and control is returned to the global context (Caller) to continue execution
Var a = 10; var fn; var bar =function(x) { var b = 20; fn(x + b); // 3. Enter fn context} fn =function(y){ var c = 20; console.log(y + c); } bar(5); // 2. Enter the bar contextCopy the code

The diagram above shows the lifecycle of the execution context (execution environment)

VO -> Variable Object, AO -> activation Object

Every time a function is called, a new execution environment is created, and VO(variable object) is assigned a new execution context. In the context of a function, VO is not directly accessible, and the active object AO continues to play the role of VO

  • VO(variable object) is the argument in the current execution context (execution environment), all function declarations, all variable declarations (here created in sequence)
  • AO(Live Object) VO(variable object) is converted to AO(live object) when a function in the current execution context (execution environment) is executed, making it accessible
VO(var object) : a fa fn var a = 1;functionFa (x) {// Local execution context (execution environment) VO(variable object) : x b fa1 var b = 20;function fa1() {}}functionFn (x) {// local execution context VO(variable object) : x b var b = 20; A = 12} // Until now all execution contexts are VO(variable object), however when the following is executed fn(1) // Fn's VO(variable object) will become AO(active object) access, When it completes, the execution environment starts to be reclaimed console.log(a) // 12Copy the code

Scope and scope chain

  • Scope refers to the area in the program where variables are defined. You can also consider the VO (variable object) of the current environment as scope. The scope chain of each execution context (execution environment) consists of the VO (variable object) of the current environment and the scope chain of the parent environment.
  • Scope can be divided into block-level scope and function scope
  • Features:
    • Declaration advance: a declaration is visible in the body of a function, and functions take precedence over variables
    • Non-anonymous self-executing functions. Function variables are read-only and cannot be modified
let foo = function() { console.log(1) };
(function foo() {foo = 10 // Assignment invalid console.log(foo)}())foo() { foo = 10 ; console.log(foo) }
Copy the code
  • The scope chain
    • A scope chain can be thought of as a list of objects containing the parent and its own variable objects, so that we can access variables or functions declared in the parent through the scope chain.
    • It consists of two parts:
      • The [[scope]] property refers to the parent variable object and scope chain, that is, the [[scope]] and AO containing the parent
      • AO: self active object

So [[scopr]] includes [[scope]], forming a chain of scopes from top to bottom.

The key of knowledge

  1. The presence of external JS scripts in the head that take a long time to load (such as never completing the download) can cause the page to become unresponsive for a long time, causing the browser to appear “dead”, which is known as the “blocking effect”.

knowledge

  1. HTML, CSS, JS loading order
  2. Js loading sequence (including variable promotion knowledge points)
  3. Render Tree construction process
  4. Rearrange, redraw
  5. From receiving the URL from the browser to starting the network request thread

HTML, CSS, JS loading order

Js placed in the head will execute immediately, blocking subsequent resource downloads and execution. Because JS may modify the DOM, the order of dom operations is not controllable without blocking subsequent resource downloads.

  • If the script tag references an external script, download the script. If the script tag references an external script, execute the script. When the script tag is executed, control is returned to the rendering engine. Resume parsing down HTML pages
  • Js execution depends on the previous style. That is, only after all the previous styles are downloaded, js will be executed, but in this case, the outer chain CSS and outer chain JS are downloaded in parallel, so CSS should be placed before JS.
  • If the external linked JS script contains defer=”true”, the JS script will be downloaded in parallel (equivalent to the browser continuing to parse the HTML page and downloading the external script from the script tag in parallel). The downloaded JS scripts will be executed sequentially after the page is fully loaded.
  • External js with async=”true” property will not depend on any JS and CSS execution. The js will be executed immediately after the download, not in written order. Since async=”true” tells the browser that JS does not modify the DOM and style, it does not have to rely on other JS and CSS. At the same time, the external script in the script tag with async property is downloaded in parallel. After the JS script with async property is downloaded, the browser stops parsing the HTML web page and starts executing the downloaded JS script until the script execution is complete and the browser resumes parsing the HTML web page.
  • If you use both the async and defer properties, the latter does not work and the browser behavior is determined by the async property

Summary: The browser first reads the HTML for parsing. In the process of parsing, the external chain CSS is loaded from top to bottom. When the default script tag is encountered, the browser will block the loading and continue rendering after loading.

Js loading sequence

  1. Preprocess before execution
  • Preprocessing skips execution statements and processes only declaration statements, again from top to bottom. All declarations, including variables and functions, are processed first before any code is executed. Even if the declaration is made below the call, the browser still declares and then invokes (executes), a phenomenon called “promotion.” So, even if a function is declared at the bottom, the function can still be executed at the front.
  • Js scope chain variable access rules:
  1. When there is a variable in the current scope to access, the variable in the current scope is used.
  2. When no variable exists in the current scope to access, it is searched in the upper scope, up to the global scope.
  1. After preprocessing, the JavaScript code performs the logical operations and function calls sequentially from top to bottom.
The above conclusion
var a = 1;
function func(){
    console.log(1, a);
    var a = 2;
    console.log(2, a);
}
function func1 (a, func2){
    console.log(3, a , func2);
    var a = 2;
    console.log(4, a , func2);
    function func2 () {
        console.log(Under the 'func1 func2'); }}function func2 () {
    console.log('global func2); } func(); func1(3, 6); console.log(5, a , func2); // The result of the preprocessing is (the creation phase of the execution context lifecycle) : the creation phase: Note that the following are the global execution contexts for the create phase: {VO: {func:function,
    func1: function,
    func2: functionFunc: {VO: {// 1 A: undefined // 3. Func1: {VO: {arguments:},}, // Find that func1 is called and immediately creates a new execution context // Note: all arguments, all function declarations, all variables declarations (here created in sequence) Func2 func2: 6},// 1 Parameter func2:functionVar a: undefined 3. Var a: undefined 3. Var a: undefined 3function func(){
    var a
    console.log(1, a);
    a = 2;
    console.log(2, a);
}
function func1 (a, func2){
    function func2 () {
        console.log(Under the 'func1 func2'); } var a; console.log(3, a , func2); A = 2; a = 2; console.log(4, a , func2); // This is the generated a variable}function func2 () {
    console.log('global func2); } a = 1 func(); func1(3, 6); console.log(5, a , func2); VO is activated as the AO global execution context: {VO: {func:function,
    func1: function,
    func2: functionFunc: {AO: {a: undefined => 2 // 2. Perform the console. The log (1 a); => a = 2; => console.log(2, a); Func1: {AO: {arguments: {parameter 1 a: 3 parameter 2 func2: 6}, func2:function, a: undefined => 2 // 3. Execute the parameter a console.log(3, a, func2); => a = 2; => variable a console.log(4, a, func2); }},} console.log(1, a); // 1 undefined second console.log(2, a); // 2 2 third console.log(3, a, func2); 3 ƒ / / 3func2 () { console.log(Under the 'func1 func2'); } console.log(4, a, func2); 2 ƒ / / 4func2 () {console.log(Under the 'func1 func2'); } Fifth console.log(5, a, func2); 1 ƒ / / 5func2 () {console.log('global func2); }
Copy the code

Render Tree construction process

To render a web page, the browser needs to complete the following steps:

  1. Process HTML tags and build DOM trees.
  2. Process CSS tags and build CSSOM trees.
  3. Merge DOM and CSSOM into a render tree.
  4. Layout according to the render tree to calculate the geometry information of each node.
  5. Draw the individual nodes to the screen.
  6. If the DOM or CSSOM is modified, you can only perform all of the above steps once more to determine which pixels need to be rerendered on the screen.

Rearrange, redraw

  • Rearrangement: DOM element changes affect element geometry, such as width and height
  • Redraw: Changes to elements do not affect geometric properties such as color
The above four knowledge points are summarized

The browser first reads THE HTML for parsing and builds the DOM tree. In the parsing process, it encounters the top-down loading of external chain CSS (the CSS is parsed and the CSSOM tree is constructed), and blocks the loading when it encounters the default script tag (but the rendering tree on the page has not been built yet, and an error will be reported if it operates the rendering tree). After loading, the forward line merges DOM and CSSOM into a rendering tree, and then layouts according to the rendering tree to calculate the geometric information of each node and draw it on the screen. At this time, DOM and CSSOM operations performed by JS will cause DOM or CSSOM to be modified. If DOM or CSSOM is modified, All of the above steps can only be performed once more to determine which pixels need to be rerendered on the screen.

The url is received from the browser and returned to the server

The first thing we need to know is that every time the browser opens a new page, it opens a separate process space (that is, the browser is multi-process), and this process space is multi-threaded. This process contains the main threads (all single threads) :

  1. The GUI thread
  2. JS engine thread
  3. Event trigger thread
  4. Timer thread
  5. Network request thread (asynchronous HTTP request thread)

URL: HTTP (protocol header) : host domain name or IP address: port number/directory path /? Parameter = 1

From the client application layer (DNS, HTTP) sending HTTP requests (network request thread, opened a thread), to the transport layer (TCP, UDP) establishing TCP/IP connections through a three-way handshake, to the network layer (IP,ARP) IP addressing, and then to the data link layer (PPP) encapsulation into frames, Finally to the physical layer (bitstream) using physical media transmission.

The server receives the request and then performs a series of operations to send whatever is returned back to the client in an HTTP packet.

Description: Domain name resolution => Initiate TCP3-way handshake => Initiate AN HTTP request after establishing a TCP connection => The server responds to the HTTP request. The browser obtains the HTML code. The browser parses the HTML code and requests resources in the HTML code

No other requests were considered

Summary page optimization

  1. The CSS block

The CSS of the home page is independent, and the rest of the CSS needs to be loaded dynamically, because the drawing of HTML will be blocked by the CSS, which can reduce the white screen time when entering the first time.

  1. The js code is placed at the end of the body tag

Prevents the browser from appearing “suspended animation”

  1. Rendering optimization

Page optimization ideas are nothing more than from the DOM node operation, as far as possible to reduce DOM operations, as far as possible in js side processing.

Take an element out of the document flow, apply multiple changes to it, and bring the element back into the document. Four basic methods:

  • Hide the element and re-display it after modification
  • Use document fragments (var fragment = Document. CreateDocumentFragment (), fragments of Chinese means fragments, document fragments is a lightweight document object, designed is used to complete this task, update, and mobile node) [recommended]
  • Copy the element to a node that is out of the document, modify it and replace it back
  • Floating elements, especially for animations, are called out of animation flow.

conclusion

The above is my second note, I am a little blank, please correct me if I write badly, I want to learn more knowledge, I hope to make friends with you, I hope my notes to provide you with a comfortable viewing experience.