This is the second article I wrote in nuggets, a question in the article is a knowledge point, suggest that we look at other articles, more access to information, it is best to sum up their own, really understand, so in the interview is not back out to the interviewer, but in their own words. The article has not finished, JS related knowledge too much.

1. Introduce anti-shake and throttling, say the difference between them, and use JS to achieve

  • Image stabilization
  1. Concept: firing the same event many times in a short period of time, the function is executed only once.
  2. Implementation: Maintains a timer that waits n seconds for the event handler to execute. If the event is triggered again within n seconds, the timer is cleared and the timer is reset. The corresponding event handler will not execute until no event is triggered within n seconds.
  3. Usage scenario: Search box association; Button submission;
  4. Code implementation
// Simple implementation
function debounce(func,wait){
  let timeout = null;
  return function(){
    const context = this;
    const args = arguments;
    if(timeout) clearTimeout(timeout)
    timeout = setTimeout(() = >{
      func.apply(context,args)
    },wait)
  }
}
// Execute immediately
function debounce(func,wait,immediate){ 
  let timeout = null; 
  return function(){ 
    const context = this; 
    const args = arguments; 
    if(immediate){ 
      constcallNow = ! timeout;if(callNow) func.apply(context,args)
      timeout = setTimeout(() = >{ 
        clearTimeout(timeout); 
      },wait) 
    } else { 
      if(timeout) clearTimeout(timeout);
      timeout = setTimeout(() = >{ func.apply(context,args) },wait) 
      } 
    } 
 }

Copy the code
  • The throttle
  1. Concept: Multiple events per unit of time, but only one event handler can be executed.
  2. Implementation: Use event stamps or timer implementation
  3. Using scene: in dealing with similar mousemove/scroll touchmove events such as when the number of control event handler triggered.
  4. Implementation code:
// Timestamp: Prev old timestamp and now new timestamp are used. Each event is triggered to determine the time difference between the two. If the specified time is reached, the function is executed and the old timestamp is reset
function throttle(func, wait){ 
  let prev = 0;
  return function(){ 
    const context = this; 
    const args = arguments; 
    const now = Date.now(); 
    if(now-prev > wait){ func.apply(context,args); prev = now; }}}// The timer mode is implemented
function throttle(func, wait){ 
   let timeout = null; 
   return function(){ 
     const context = this; 
     const args = arguments; 
     if(! timeout){ timeout =setTimeout(() = >{ 
         func.apply(context,args) 
         clearTimeout(timeout); 
       },wait) 
     } 
   } 
 }
Copy the code

2. Talk about closures and their application scenarios

  • Concept: Closures give the function access to a defined lexical scope when a function is called outside of its lexical scope. Closure generated when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope. Essentially any asynchronous task that uses a callback function, such as timer, event listener, Ajax request, is using a closure.
  • Features: Local active objects are destroyed after normal functions are executed. However, because the closure’s scope chain contains the function’s live object, this prevents the variable from being destroyed after the function completes execution and can cause a memory leak if used improperly.
  • Use scenarios: simulate private variables; Asynchronous callbacks are essentially using closures.

3. Browser process vs. thread, js single thread brings benefits?

  • The concept of process: a program with some independent functions is about a running activity on a data set, which is an independent unit of the system for resource allocation and scheduling.
  • Thread concept: A process may contain many sequential execution streams, each of which is a thread.
  • The difference between a process and a thread: a process is the smallest unit of resources allocated by the operating system, and a thread is the smallest unit of program execution. A process can be composed of one or more threads, which can be understood as different execution paths of code in a process. For example, when you open a TAB page, is to create a process, a process can have multiple threads, such as HTTP requests render threads, js engine threads, thread, etc., when you launch a request, is to create a thread, when after the request, this thread may be destroyed.
  • Browser process classification:
  1. User interface thread: responsible for browser interface display, user interaction (address bar forward, backward), etc.
  2. Browser process: The main process of the browser (responsible for coordination and control), which has only one process. Responsible for the management of each page, create and destroy other processes; Network resource management, download and so on; Communicate instructions between the user interface and the rendering engine.
  3. Rendering process (important) : often referred to as browser kernel; Each TAB page has a rendering process that does not affect each other; The rendering process is multi-threaded, including Ajax request, page rendering, event trigger thread, UI thread, timer thread, wherein UI thread and JS thread are mutually exclusive, sharing the same thread.
  4. Persistent layer processes: Store cookies, sessionStorage, localStorage, indexedDB, etc.
  • Browser rendering thread classification:
  1. GUI rendering thread: responsible for rendering the browser interface, parsing HTML/ CSS, building the Render tree, layout and drawing, etc., when the interface needs to be redrawn or when some operation causes backflow, this thread executes;
  2. JS engine thread (main thread) : THE JS kernel is responsible for processing JS scripts, parsing JS scripts, and running code (V8 engine). The JS engine thread and GUI rendering thread are mutually exclusive.
  3. Event trigger thread: When JS execution meets asynchronous operation (such as setTimeout/ Ajax request), it will add the corresponding event to the corresponding thread (timer thread/HTTP request thread). When the asynchronous operation has the result, it will notify the event triggering thread to add their callback operation to the event queue, and so on when JS is idle to deal with; When the corresponding event is triggered (onclick, onload), the event-triggering thread adds the corresponding callback operation to the event queue.
  4. Timer trigger thread: setTimeout and setInterval thread,
  5. Asynchronous HTTP request thread: When an HTTP request is executed, the asynchronous request operation is placed in the HTTP request thread. When the response is received, the event-triggering thread adds the callback function to the event queue and waits for execution.
  • Single threaded JS benefits: Avoid dom rendering conflicts.

4. What do you know about the Event loop

  • Concept: In order to improve CPU utilization, JS divides tasks into synchronous tasks and asynchronous tasks. Synchronous tasks are executed sequentially in the main thread, and asynchronous tasks are put into the callback queue. The main thread will form an execution stack. After all synchronization tasks in the execution stack are completed, the main thread will read an event from the callback queue, put it into the execution stack, and empty the execution stack when the event is finished. The event trigger thread will then read the next event in the call queue and put it on the execution stack. This process is cyclic, so this mechanism is called event loop. (Outside of the main thread, the event-firing thread manages the task queue.)

5. What are macro tasks and micro tasks?

  • Common macro tasks (any JS code scheduled to be executed by a standard mechanism) : program initialization; Event triggers a callback. SetTimeout; SetInterval. requestAnimationFrame
  • Common microtasks: promise.then; Promise. Catch; Promise. Finally; MutationObserver; queueMicrotask
  • The difference between:
  1. The browser executes a macro task, then executes the microtasks in the current stack, then renders, and then executes the next macro task.
  2. Microtasks are not in the same task queue as macro tasks.
  3. Microtasks can add new microtasks to the queue and complete all of the microtasks before the next task starts, providing a better level of access.

6. Describe your understanding of prototyping and explain what a prototype chain is. What problem does the prototype chain solve?

  • Prototype: Each function has a prototype attribute that points to an object that is the prototype of the object instance created by calling the constructor. The advantage of using stereotypes is that all object instances share the properties and methods it contains.
  • Prototype chain: Each constructor has a Prototype property pointing to the prototype, a constructor property pointing to the constructor, and an internal pointer _proto_ to the prototype in the instance. If a stereotype is an instance of another type, that means it has a _proto_ pointer inside it to another stereotype, and so on, creating a chain of stereotypes between the instance, constructor, and stereotype.
  • Function: Through the prototype chain, one object can inherit the properties and methods of another object, and realize the instance to share the properties and methods.

7. Talk about ES5 inheritance and ES6 inheritance

  • Composite inheritance (ES5) : combines stereotype chains and borrowed constructors, using stereotype chains to inherit properties and methods on stereotypes, and borrowing constructors to inherit instance properties. This allows for reuse of methods in prototypes and allows each instance to have its own attributes. The downside is that the superclass constructor is executed twice;
function SuperType(name){ 
  this.name = name; 
  this.colors = ['red'.'blue'.'yellow'] 
} 
SuperType.prototype.sayName = function(){ 
  console.log('hello world')}function SubType(){ 
// Functions are simple objects that execute code in a particular context
  SuperType.call(this,name) 
} 
SubType.prototype = new SuperType(); 
let instance1 = new SubType()
Copy the code
  • Parasitic composite inheritance (ES5 best) : Use a hybrid prototype chain inheritance approach by borrowing constructor inheritance properties. Instead of assigning to a subclass stereotype by calling the superclass constructor, get a copy of the superclass stereotype and assign to the subclass directly.
function inheritPrototype(subType,superType){ 
  let prototype = object(superType.prototype) // Create the parent constructor prototype object
  prototype.constructor = subType // Enhance the object to solve the problem of default constructor loss caused by rewriting the prototype
  subType.prototype = prototype; // Assign an object
} 
function SuperType(name){ 
  this.name = name; 
  this.colors = ['red'.'blue'.'yellow'] 
} 
SuperType.prototype.sayName = function(){ 
  console.log(this.name) 
} 
function SubType(name,age){ 
  SuperType.call(this,name); 
} 
inheritPrototype(SubType,SuperType);
Copy the code
  • Class inheritance (ES6 inheritance method)

Use the extends keyword and call super in the subclass constructor (think of parent-call (this,value))

class Parent { 
  constructor(name){ 
    this.name = name 
  } 
  getName(){ 
    console.log(this.name) 
  } 
} 
class Child extends Parent { 
  constructor(age){ 
    super(value); 
    this.age = age 
  } 
} 
let child = new Child('dandan'); 
child.getName()
Copy the code
  • The difference between parasitic combinatorial inheritance and class inheritance: After compiling ES6 code into ES5 with Babel, it is found that the core of class inheritance is parasitic combinatorial inheritance.

8. How to judge the type?

  • Typeof determines the primitive type (Number, String, Undefined, Boolean, Symbol)
typeof 1 // 'number'
typeof '1' // 'string' 
typeof undefined // 'undefined'
typeof true // 'boolan' 
typeof Symbol // 'symbol': represents unique values
Copy the code
  • Instanceof determines the type of reference: Used to check if the constructor’s prototype property appears on the prototype chain of an instance object (as opposed to the instance and constructor).
function Foo(){}; 
let myFoo = new Foo(); 
console.log(myfoo instanceof Foo) // true 
console.log(myfoo instanceof Object) // true
Copy the code
  • Array.isarray () checks whether a value is an Array.
Array.isArray([1.2.3]) //true
Copy the code
  • Object. The prototype. The toString () to this method, returns a form such as “[Object] XXX” string.. You can judge almost any type of data.
// Boolean type, tag is "Boolean"
Object.prototype.toString.call(true); // => "[object Boolean]" 
// Number type, tag is "Number"
Object.prototype.toString.call(1); // => "[object Number]" 
// The tag is "String".
Object.prototype.toString.call(""); // => "[object String]" 
// Array type, tag "String"
Object.prototype.toString.call([]); // => "[object Array]" 
// Arguments type, tag = "Arguments"
Object.prototype.toString.call((function() { return arguments; }) ());// => "[object Arguments]" 
// Function type, tag is "Function"
Object.prototype.toString.call(function(){}); // => "[object Function]" 
// Error type (including subtypes), tag "Error"
Object.prototype.toString.call(new Error()); // => "[object Error]" 
// RegExp type, tag "RegExp"
Object.prototype.toString.call(/\d+/); // => "[object RegExp]" 
// Date type, tag is "Date"
Object.prototype.toString.call(new Date()); // => "[object Date]" 
// Other type, tag is "Object"
Object.prototype.toString.call(new class {}); // => "[object Object]"
Copy the code

9. Determine the binding of this

  • Default binding: in strict mode, bind to undefined; In non-strict mode, bind to global objects;
  • Implicit binding: the function is called in a context object, and this is bound to that context object (obj.foo());
  • Display bindings: The function is called through call, apply, bind, so this is bound to the specified object; Fn. Call (target, 1, 2); Fn. Apply (target, [1, 2]); Fn. Bind (target) (1, 2)
  • New binding: if the function is new, this binds to the newly created object in new.
  • The arrow function does not have its own this; its this inherits from this in the previous code block;
  • New Binding > Explicit Binding > Implicit Binding > Default binding;

10. The implementation principle of Call /apply/bind and how to implement it internally

  • Call, apply, and bind are the three methods that hang on the Function object. They must be called as a Function. They can be called either to specify this for the function to be executed or to be passed as an argument.
  • Call way
func.call(target,1.2); // Call a function method with a specific object and pass an argument to the function
func.apply(target,[1.2]); 
func.bind(target)(1.2)
Copy the code
  • Implement a call function
Function.prototype.call = function(context){ 
  if(typeof this! = ="function") {throw new Error("not a function"); 
  }; // Determine if the calling object is a function, and throw an error if it is not
  context = context ? context : window // Bind to window if context is empty
  const key = Symbol('key'); // Create a unique attribute value to prevent overwriting existing attributes
  context[key] = this; // Add an attribute to the context, where this refers to the current function
  const rest = [...arguments].slice(1) // Get parameters other than the object to which this points
  const res = rest.length > 0? context[key](... rest) : context[key]()// Implicitly bound, the current function's this refers to the context
  delete context[key] // Delete the attribute fn
  return res
}
Copy the code
  • Implement an apply function
Function.prototype.apply = function(context,args){
  if(typeof this! = ='function') {throw new Error('not a function')
  } 
  context = context ? context : window 
  const key = Symbol('key') 
  context[key] = this 
  const res = args.length > 0? context[key](... args) : context[key]()delete context[key] 
  return res 
}
Copy the code
  • Implement a bind function
Function.prototype.bind = function(context,... rest){ 
  if(typeof this! = ='function') {throw new Error('not a function') 
  } 
  context = context ? context : window 
  const func = this 
  return function(){ 
    const args = [].slice.call(arguments) 
    return func.apply(context, rest.concat(args)) 
  } 
}
Copy the code
  • role
  1. Determine type
Object.prototype.toString.call(obj)
Copy the code
  1. Class array borrowing method
let arrayLike = { 
  0:'java'.1:'html' 
} 
Array.prototype.push.call(arrayLike,'css'.'node') 
console.log(arrayLike) // {0:'java',1:'html',2:'css',3:'node'}
Copy the code
  1. Get the maximum and minimum value of an array: Using Apply to pass an array directly as an argument to a call method reduces the need to expand an array asynchronously
let arr = [1.8.9.15.23]; 
const max = Math.max.apply(Math,arr); 
const min = Math.min.apply(Math,arr); 
console.log(max) / / 23
console.log(min) / / 1
Copy the code
  1. The subclass constructor calls the parent constructor internally, thereby inheriting instance properties.

11. Why does variable promotion exist in JS?

  • Assignment of a variable performs two actions (compile first, then run). First, the compiler declares a variable in the current scope (if it has not been declared before), and then at run time the engine looks up the variable in the scope and assigns a value to it.

12. Light copy, distinction and handwriting

  • Shallow copy: A shallow copy creates a new object with an exact copy of the original object’s property values. If the property is of a primitive type, it copies the value of the primitive type, if the property value is of a reference type, it copies the memory address, so if one object changes the address, it affects the other object.

  • Deep copy: To make a full copy of an object out of memory, creating a new area of heap memory to store the new object, and modifying the new object does not affect the original object

  • The way to implement shallow copy
  1. Object.assign()
  2. The _.clone method of the lodash library
  3. Expansion operator…
  4. Array.prototype.concat()
  5. Array.prototype.slice()
  6. Handwritten shallow copy
  • Implementing deep copy
  1. Json.parse (json.stringify) : Can implement deep copies of arrays or objects, but can’t handle functions and regs;
  2. The _. CloneDeep method of the lodash library
  3. Handwritten recursive methods (there are a few types to consider, just a few here)
// Determine the type
function cloneType(target){ 
  return Object.prototype.toString.call(target) 
} 
/ / copy
function cloneDeep(target){ 
  let cloneTarget; 
  if(typeoftarget ! = ='object') return target
  let type = cloneType(target) 
  if(type.includes('Null')) return null 
  if(type.includes('Date')) return new Date(a)if(type.includes('RegExp')) return new RegExp(target) 
  if(type.includes('Array')){ 
    cloneTarget = [] 
    cloneTarget = target.map(item= > { return cloneDeep(item) }) 
    return cloneTarget 
  } 
  if(type.includes('Object')){ 
    cloneTarget = {} 
    let keys = Object.keys(target) 
    for(key of keys){ 
      cloneTarget[key] = cloneDeep(target[key]) 
    } 
    return cloneTarget 
  } 
}
Copy the code

13. Describe the implementation process of new

  • Steps:
  1. Generates a new object
  2. Link to the prototype
  3. Binding this
  4. Return a new object
  • implementation
function create(Con, ... args){ 
  let obj = {} // Create an empty object
  Object.setPrototypeOf(obj, Con.prototype) Method in ES6 that sets the prototype of a specified object
  let result = Con.apply(obj,args) // bind this and execute the constructor
  return result instanceof Object ? result : obj // Make sure the return value is an object
}
Copy the code
  • Add: new has a return value and no return value difference

Normally, constructors do not return values, but the user can actively return objects to override the normal creation of the object; If the return returns an object, it overwrites the object that was created normally. If the return value is a primitive type, the normal return object is not overridden;

14. Why 0.1+0.2! = 0.3?

  • Cause: Precision loss occurs in the process of base conversion and logarithmic operation
  1. Base conversion: the computer cannot directly calculate the decimal digits, so it needs to convert them to binary in accordance with IEEE 754 specifications. 0.1 and 0.2 will be looped endlessly after converting to binary, and due to the limitation of the mantras of IEEE 754, it needs to cut off the redundant bits behind, so the accuracy has been lost in the conversion between bases.
  2. Order operation: The operation needs to order operation, this part may cause precision loss.
0.1 -> 0.0001100110011001. (Infinite loop)0.2 -> 0.0011001100110011. (Infinite loop)0.1 + 0.2= = =0.30000000000000004 // true
Copy the code
  • To solve
// toFixed() converts the operation to a string
parseFloat((0.1 + 0.2).toFixed(10= = =))0.3 // true
Copy the code

Var /let/const

  • In the global scope, variables declared by var are attached to Windows, but let and const are not.
  • Variables declared by var have variable promotion, while let and const do not.
  • Let and const declarations form block-level scopes and can only be accessed within the block-level scope, not across blocks.
  • Let and const cannot declare variables of the same name in the same scope. Var does.
  • Variables declared by let and const cannot be used before they are declared.

16. Globally, a variable declared by var hangs under a window. Where does a variable declared by let (const) hang?

let pjj = 'a';
var person = 'b';
debugger
Copy the code

As shown in the figure, let and const variables declared globally hang under block-level scope script.

17. Array flattening

  • ES6 flat(level) : The level parameter indicates the number of layers leveled;
[1.2[3.4]].flat() // [1,2,3,4] level 1 layer
[1.2[3[4.5]]].flat(2) // [1, 2, 3, 4, 5
Copy the code
  • Serialized regex: Converts the array passed in to a string, then removes the square brackets using a regular expression.
let arr = [1[2[3[4.5]]].6]; 
function flatten(arr){ 
  let str = JSON.stringify(arr); 
  str = str.replace(/(\[||\])/g.' '); 
  str = '[' + str + '] '; 
  return JSON.parse(str); 
}
Copy the code
  • Reduce () recursion (common)
let arr = [1[2[3[4.5]]].6]; 
function flatten(arr){ 
  return arr.reduce((acc,cur) = >{ 
    return acc.concat( 
      Array.isArray(cur) ? flatten(cur) : cur 
    ) 
  },[]) 
}
Copy the code
  • Split () and toString() are handled together
let arr = [1[2[3[4.5]]].6]; 
function flatten(arr){ 
  return arr.toString().split(', ')}Copy the code

18. What is the same-origin policy?

  • Concept: an important security policy that restricts how documents from one source or scripts loaded by it can interact with resources from another source. It can help block malicious documents and reduce the number of vectors that can be attacked. The protocol, domain name, and port are the same.
  • Restricted contents of the same Origin policy:

1. Storage contents such as cookies, localStorage, and indexedDB cannot be obtained. 2. After the AJAX request is sent, the returned result is blocked by the browser.

19. Cross-domain browser mode?

  • JSONP
  1. How it works: JSONP does this by dynamically creating
  2. Advantages: Simple, good compatibility
  3. Disadvantages: Only support get method, insecure, may be subject to XSS attacks;
function jsonp({ url, params, callback }) { 
  return new Promise((resolve, reject) = > { 
    let script = document.createElement('script')
    // Define the callback function and mount it on the window object so that it can be accessed directly from the loaded JS code
    window[callback] = function(data) { 
      resolve(data) 
      document.body.removeChild(script) } params = { ... params, callback }// wd=b&callback=show 
    let arrs = [] 
    for (let key in params) { 
      arrs.push(`${key}=${params[key]}`) 
    } 
    script.src = `${url}?${arrs.join('&')}` 
    document.body.appendChild(script) // Return the callback function show("hello world")})}; jsonp({url: 'http://localhost:3000/say'.params: { wd: '123456' }, 
   callback: 'show'
 }).then(data= > { 
   console.log(data) 
 })
Copy the code
  • CORS

How it works: Servers can choose to Allow cross-domain requests to Access their resources, and if the server decides to respond to the request, it should send the Access-Control-Allow-Origin header, containing the same source, or * if the resource is public

  • postMessage

The postwindow.postMessage () method is called on a window to send a MessageEvent message. The window that receives the message (targetOrigin) is free to process this event as needed.

// Window to send messages
// data: data to be sent to another window
// targetOrigin: Specifies which Windows receive message events. The value can be a string * or a URL
postWindow.postMessage(data,targetOrigin,[transfer]) 
// The window to receive messages
window.addEventListener('message',receiveMessage,false) 
function receiveMessage(event){ 
  event.data // Data passed from other Windows
  event.origin // The origin of the message to send when postMessage() is called
  event.source // The introduction of a window object that sends messages
}
Copy the code
  • websocket

Principle: The interactive communication session can be opened between the user’s browser and the server. After the connection is established, the Server and client of WebSocket can actively send or receive data to each other.

const socket = new WebSocket('ws://localhost:8080'); 
socket.addEventListener('open'.event= >{ socket.send('hello') // Send data to server})
socket.addEventListener('message'.event= >{ console.log('Message from server ', event.data); // Receive data from the server})
Copy the code
  • Nginx reverse proxy

Principle: Requests from a server to a server do not follow the same origin policy. When a user visits a web site, the nGINx server will first visit the nginx server, and then the NGINx server will select a less stressed server from the server cluster and direct the access request to that server.

20. Browser caching

  • Function: reuse the obtained resources, improve the overall loading speed of the web page;
  • Cache classification:

  • Browser caching: Strong caching (through both Expires and cache-Control response headers)
  1. Expires: This describes an absolute time when the cache Expires, which is returned by the server. Expires is limited to local time, and changing the local time can invalidate the cache.
  2. Cache-control: Specifies a relative time when a Cache Expires, max-age=259000, with priority over Expires.
Cache-Control: no-cache // Forces the source server to validate again
Cache-Control: no-store // Do not cache data locally
Cache-Control: public // Can be cached by all users, including terminals and intermediate proxy servers such as CDN
Cache-Control: private // Can only be cached by terminal browser, not by relay server
Cache-Control: max-age=256000 // Specify the relative time at which the cache expires
Copy the code
  • Browser cache mechanism: negotiated cache (using last-Modified && if-modified-since and ETag && if-none-match)
  1. Last-modified && If Modified – Since: When the browser requests a resource for the first time, the server adds last-Modified to the response header. When the browser requests the resource again, it adds an if-Modified-since field to the request header. The server compares the two times and returns 304 if they are the same, otherwise returns the new resource and updates last-Modified.
  2. ETag && if-none-match: ETag indicates the unique identifier of the file. If the file is changed, the ETag will be recalculated. The server sends the ETag field and the browser sends if-none-match when it requests it again. The server compares the two values and returns 304 If they are the same, otherwise returns a new resource and updates last-Modified.

21. Browser rendering flow

  1. Build a DOM tree: Parse HTML files to build a DOM tree.
  2. Generate style sheets: Parse CSS files to generate style sheets;
  3. Build a Render tree: Associate the DOM tree with the stylesheet to build a render tree.
  4. Determine node coordinates: Layout rendering tree (Layout/reflow), responsible for the calculation of the size and position of elements in the rendering tree;
  5. Draw the page: display the coordinates according to the Render tree and nodes, and then call the paint method for each node to draw them;

22. Type a URL into the address bar to render the page completely. What happens in between?

  • DNS Domain name resolution: Resolves a domain name into an IP address.

DNS domain name resolution process (recursive query and iterative query) : Browser cache – > system cache – > hosts file – > Router cache – > DNS cache – > DNS recursive query

  • TCP connection: TCP three-way handshake;
  1. First handshake: The client sends a SYN packet to the server with the INITIAL ISN of the client.
  2. Second handshake: After receiving a SYN packet from the client, the server responds with its OWN SYN packet, and specifies its initial ISN. The ISN + 1 of the client is used as an ACK value, indicating that the server has received a SYN from the client.
  3. Third handshake: After receiving a SYN packet, the client sends an ACK packet with the ISN+1 of the server as the ACK value, indicating that the CLIENT has received a SYN packet from the server. Then, the two sides establish a connection.

Why is the three-way handshake required? Check whether the receiving and sending capabilities of both parties are normal. Specify your own initialization sequence number to prepare for subsequent reliable transmission; If HTTPS is used, the three-way handshake also performs digital verification and encryption key generation.

  • After a TCP connection is established, an HTTP request is sent.
  • The server processes the request and returns HTTP packets;
  • The browser parses the rendered page;
  1. HTML parsing, DOM construction;
  2. CSS parsing, CSS rule tree generation;
  3. Combine DOM tree and CSS rules to generate render tree;
  4. Render tree (Layout /reflow), responsible for the size of each element, position calculation;
  5. Render tree (paint), render the page pixel information;
  • Disconnection: TCP four waves;
  1. First wave: The client sends a FIN packet and specifies the client serial number.
  2. Second wave: After receiving the FIN packet, the server sends an ACK packet and uses the serial number of the client +1 as the sequence number value of the ACK packet. If the server serial number is specified, the packet is received.
  3. Third wave: If the server also wants to disconnect, the server sends a FIN packet with a specified sequence number as the first wave from the client.
  4. Fourth wave: After receiving a FIN packet, the client sends an ACK packet and uses the sequence number +1 of the server as the sequence number of its own ACK packet.

23. What is Click through?

  • Reason: the page has two elements, element B is above element A. When element B is clicked, element B is hidden and element A’s click event is triggered. This is because in mobile browser, the execution sequence of click events is touchStart — touchmove — touchend — click, because click is delayed by 300ms. When the touchStart event is triggered on B, B is hidden. 300ms later, The click event of A is raised.
  • Solutions:
  1. The introduction of fastclick;
  2. Call preventDefault on the Touchend event, cancel the click event;