preface

According to the front end self-check list sorted out by the gods, they sorted out the answer, but also convenient for their own learning.

First, JavaScript basics

Variables and types

1.JavaScript specifies several data types

Js defines 8 data types, including: Undefined,Null,Boolean, Number, String, Object, Symbol,BigInt

2. What are the underlying data structures of JavaScript objects

JavaScript primitives are stored directly on the stack by value (Undefined, Null, non-new booleans, numbers, and strings). Each type of data occupies a certain amount of memory and is automatically allocated and freed by the system. The benefit is that memory can be reclaimed in a timely manner, making it easier to manage memory space compared to the heap.

JavaScript reference type data is stored in the heap (objects, arrays, functions, etc., which are copied and new). In fact, it is not accurate to say stored in the heap, because the address pointer of the reference type data is stored in the stack, when we want to access the value of the reference type, we need to get the address pointer of the object from the stack, and then find the data needed in the heap through the address pointer.

3 Symbol type in the actual development of the application, manual implementation of a simple Symbol

1. Use symbols instead of constants

const TYPE_AUDIO = Symbol()
const TYPE_VIDEO = Symbol()
const TYPE_IMAGE = Symbol()
Copy the code

2. Use Symbol as the object attribute name (key)

Const PROP_NAME = Symbol() const PROP_AGE = Symbol() let obj = {[PROP_NAME]: "1"} obj[PROP_AGE] = 18Copy the code

3. Use Symbol to define class private properties/methods

// a.js const PASSWORD = Symbol() class Login { constructor(username, password) { this.username = username this[PASSWORD] = password } checkPassword(pwd) { return this[PASSWORD] === pwd } } export default Login // b.js import Login from './a' const login = new Login('admin', '123456') login.checkPassword('123456') // true login.PASSWORD // oh! no! login[PASSWORD] // oh! no! login["PASSWORD"] // oh! no!Copy the code

Because the Symbol constant PASSWORD is defined in the module where A. Js is located, the outside module cannot obtain this Symbol, and it is impossible to create an identical Symbol (because Symbol is unique). Therefore, the Symbol of this PASSWORD can only be used within A. js, so the class attributes defined by it cannot be accessed outside the module, achieving a privatized effect.

4. Registering and retrieving Symbol instances created in the global Symbol Window are always unique, and we need to maintain a shared Symbol in all of these window environments. In this case, we need to use another API to create or obtain the Symbol. That is symbol.for (), which can register or obtain an inter-window global Symbol instance:

For ('global_symbol_1') // Obtain the global Symbol gs1 === gs2 // trueCopy the code

4. The specific storage form of JavaScript variables in memory

Basic types are stored in the simple data section in the stack memory, their values are fixed, the size of the stored in the stack space, through access to a reference type by value is stored in the object in the heap memory, value size is not fixed, stack memory to store the object access address pointing to the object in the heap memory, JavaScript does not allow direct access to the location of heap memory, So when you manipulate an object, you actually manipulate a reference to the object

let a1 = 0; // let a2 = "this is string"; // let b = {x: 10}; Let c = [1, 2, 3]; let c = [1, 2, 3]; // The variable c resides on the stack, and [1, 2, 3] resides on the heap as an objectCopy the code

5. The built-in objects corresponding to the basic types and the boxing and unboxing operations between them

Built-in objects: Object is the parent Object of all objects in JavaScript. Data encapsulation class objects: Object, Array, Boolean, Number, and String other objects: Function, Math, Date, RegExp, and Error. Arguments: An operation to convert a basic data type to the corresponding reference data type. There are implicit boxing and display boxing implicit boxing

Let a = 'sun' let b = a.indexof('s') // 0 // return subscriptCopy the code

The actual steps of the above code in the background are as follows:

let a = new String('sun')
let b = a.indexof('s')
a = null
Copy the code

Implementation mechanism:

1. Create an instance of String. 2. Invoke the specified method on the instance. 3. Destroy the instance.

Let a = new String(‘sun’) let a = new String(‘sun’)

Unboxing: Unboxing, as opposed to boxing, converts a reference type to primitive data, usually through valueof() and toString () methods for reference types

let name = new String('sun') let age = new Number(24) console.log(typeof name) // object console.log(typeof age) // Console. log(typeof age.valueof ()); // number // 24 Basic number types console.log(typeof name.valueof ()); // number // 24 Basic number types console.log(typeof name.valueof ()); // string // 'sun' base character type console.log(typeof age.tostring ()); // string // '24' basic character type console.log(typeof name.tostring ()); // string // the basic character type of 'sun'Copy the code

Understand value types and reference types

7. Null vs. undefined

Null means “no object”, meaning there should be no value. Typical usage:

(1) as the parameter of the function, indicating that the parameter of the function is not an object. (2) as the end of the object prototype chain.

Undefined means “missing value”, that is, there should be a value here, but it is not defined yet. Typical usage:

(1) If a variable is declared but not assigned, it is undefined. (2) When the function is called, the argument that should be provided is not provided, which is equal to undefined. (3) The object has no assigned attribute. The value of this attribute is undefined. (4) If the function does not return a value, undefined is returned by default.

8. There are at least three ways to identify JavaScript data types, and their strengths and weaknesses

1, typeof :(can make an accurate judgment for basic types, but for reference types, a little bit more difficult)

Typeof returns a string representing the data type, including number, Boolean, string, object, undefined, and function.

2, instanceof

If A is an instanceof B, return true; if A is an instanceof B, return true; if A is an instanceof B, return true. Otherwise return false. Note in particular that Instanceof checks for prototypes

3 Object.prototype.toString

ToString is a method on an Object prototype that returns the specific type of its caller by default. More strictly, it is the type of the Object pointed to by the toString runtime. The type returned is in the format [Object, XXX], where XXX is the specific data type, including: String, Number, Boolean, Undefined, Null, the Function, the Date, the Array, the RegExp, Error, HTMLDocument,… Basically all object types can be retrieved using this method.4 Constructor View the corresponding constructor of the objectConstruvtor is automatically generated under the prototype of the corresponding object, which is added by the program when we write a constructor

9. How can implicit type conversions be avoided or skillfully applied

10. The reasons for the loss of decimal precision, the maximum number that JavaScript can store, the maximum safe number, the method of JavaScript to deal with large numbers, and the method to avoid the loss of precision

0.1+0.2 is not equal to 0.3, because the computer to calculate the first conversion into binary, two floating point number with binary is infinite bits, IEEE754 standard with 64 bits (1 bits used to represent the symbol bit, 11 to represent the index, 52 bits to represent the mantis) will truncate the following bits, and then converted into decimal, there is an error.

Maximum number:

For integers, the probability of front-end problems is probably low, since very few businesses need to use very large integers, and as long as the results don’t exceed Math.pow(2, 53), there is no loss of precision.

For decimal, the probability of front-end problems is still a lot of, especially in some e-commerce sites involving amounts and other data. Solution: Place decimals in place integers (multiples) and shrink back (divides multiples)

The safest number – math.pow (2, 53)-1, to +Math.pow(2, 53)-1

Prototype and prototype chain

1. The basic implementation principle of Instanceof: Manually implement an Instanceof

function new_instance_of(leftVaule, rightVaule) { let rightProto = rightVaule.prototype; // Take the prototype value of the right expression leftVaule = leftvaule.__proto__; While (true) {if (leftVaule === null) {return false; } if (leftVaule === rightProto) { return true; } leftVaule = leftVaule.__proto__ } }Copy the code

2. Several ways to implement inheritance and their advantages and disadvantages

Function SuperType(){this.property = true; } SuperType.prototype.getSuperValue = function(){ return this.property; } function SubType(){ this.subProty =false; } SubType.prototype = new SuperType(); var instance = new SubType(); Console. log(instance.getsupervalue ()) // Use constructor function SuperType(name) {this.name = name; } function SubType(){ SuperType.call(this, 'demo'); this.age = 18; } var instance = new SubType(); console.log(instance.name); console.log(instance.age); Function SuperType(name){this.name = name; this.colors = ['red']; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name,age) { SuperType.call(this,name); this.age = age; } SubType.prototype = new SuperType(); SubType.prototype.sayAge = function(){ console.log(this.age); } var instance = new SubType('demo',18); instance.sayAge(); instance.sayName(); Function object(o) {function F(){}; F.prototype = o; return new F(); } var person = { name: 'Tom'} var anotherPerson = object(person) console.log(anotherperson.name) var clone =Object.create(original); clone.sayHi = function () { console.log('hi'); } return clone; } var person = { name: 'tom' } var anotherPerson = createAnother(person); console.log(anotherPerson.name) anotherPerson.sayHi(); Function SuperType(name) {this.name = name; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name,age){ SuperType.call(this,name); this.age = age; } function inheritPrototype(subType,superType){ var prototype = Object.create(superType.prototype); prototype.constructor =subType; subType.prototype = prototype; } inheritPrototype(SubType,SuperType); var person = new SubType('zhangsan',18); person.sayName()Copy the code

3. Can describe the detailed process of new an object, manual implementation of a new operator

function Person (name,age){ this.name = name; this.age = age; this.say = function () { console.log("I am " + this.name) } } function realizeNew(){ let obj = {}; let Con = [].shift.call(arguments); obj.__proto__ = Con.prototype; let result = Con.apply(obj,arguments); return typeof result === 'object'? Result: obj} var person1 =realizeNew(Person,' Person ')Copy the code

4. Understand the underlying implementation of ES6 class construction and inheritance

Scope and closure

1. Understand lexical and dynamic scopes

Lexical scope, the scope of a function determines (depending on where the function is defined) the dynamic scope of a function, and the scope of a function determines (depending on the function called) the lexical scope of JS

2. Understand JavaScript scopes and scope chains

A scope is an independent domain that keeps variables from leaking and being exposed. In other words, the greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict. Before ES6, JavaScript had no block-level scope, only global scope and function scope. With the advent of ES6, we have ‘block-level scope’, which can be embodied by the addition of the let and const commands.

Function outFun2() {var inVariable = "inVariable "; } outFun2(); // Execute this function first, otherwise you don't know what's inside console.log(inVariable); // Uncaught ReferenceError: inVariable is not definedCopy the code

When a scope chain uses a variable in JavaScript, the JavaScript engine tries to find the value of the variable in the current scope. If the variable is not found, it looks for the external scope and continues to do so until the variable is found or the global scope is reached.

If the variable is still not found, it either implicitly declares the variable in global scope (if not in strict mode) or returns an error. ####3. Understand the execution context stack of JavaScript and use stack information to quickly locate problems. The execution context is an abstract concept of the environment in which the JavaScript code is being parsed and executed.

Types of execution context There are three types of execution context: global execution context: only one, the global object in the browser is the Window object, and this points to this global object. Function execution contexts: There are an infinite number of them, which are created only when a function is called, and a new execution context is created each time a function is called. Eval function execution context: Refers to code that runs in the Eval function, rarely used and not recommended.

Execution stack The execution stack, also known as the call stack, has a LIFO (last in, first out) structure for storing all execution contexts created during code execution. When JS code is first run, a global execution context is created and pushed into the current execution stack. Each time a function call occurs, the engine creates a new function execution context for that function and pushes it to the top of the current execution stack. According to the execution stack LIFO rule, when the top function is completed, its corresponding function execution context will Pop out of the execution stack, and the control of the context will be moved to the next execution context of the current execution stack.

The execution context is created in two stages: 1) the creation stage; Step 1: Determine the value of this, also known as this Binding. 2. The LexicalEnvironment component is created. 3. The VariableEnvironment component is created. This Binding: In the global execution context, the value of This points to the global object, and in the browser, the value of This points to the window object. In the context of function execution, the value of this depends on how the function is called. If it is called by an object reference, then the value of this is set to that object, otherwise the value of this is set to global object or undefined (in strict mode) lexical context In lexical context, there are two components: The environment record is the actual location where variable and function declarations are stored. A reference to an external environment means that it has access to its external lexical environment. Variable environment: It is also a lexical environment whose EnvironmentRecord contains bindings created by VariableStatements in this execution context. As mentioned above, the variable environment is also a lexical environment, so it has all the attributes of the lexical environment defined above. In ES6, the difference between the LexicalEnvironment component and the VariableEnvironment component is that the former is used to store function declarations and variable (let and const) bindings, while the latter is only used to store variable (var) bindings. During the creation phase, the code is scanned and parsed with variable and function declarations, where the function declarations are stored in the environment, Variables are set to undefined (in the case of var) or left uninitialized (in the case of let and const). This is why you can access variables defined by var (albeit undefined) before declaring them. But if you access variables defined by let and const before the declaration, you will be prompted for the reference error.

This is what we call variable lifting.

4. The principle of this and the value of several different usage scenarios

I. This Principle

This refers neither to the function itself nor to the lexical scope of the function, but to the object on which the function is called!

Two, use scenarios

A) Ordinary function call, this refers to Window

Var name = 'kaka '; Function cat(){var name = 'I '; console.log(this.name); / / kaka console. The log (this); //Window {frames: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, } } cat();Copy the code

(2) Object method, this refers to the object

1. At one level of the scope chain, this refers to the object

Var name = 'kaka '; Var cat = {name:' fish ', eat:function(){console.log(this.name); }} cat.eat();Copy the code

2. In a multi-layer chain of scopes, this refers to the object at the closest level to the method

Var name = 'kaka '; Var cat = {name: eat1:{name: eat2:function(){console.log(this.name); // year}}} cat.eat1.eat2();Copy the code

If cat.eat1.eat2 is assigned to eat3, what is the value of eat3()?

var eat3 = cat.eat1.eat2; eat3(); / / kakaCopy the code

Eat3 () is the actual call to the root object window, so this refers to window, this.name= card

(3) constructor call, this refers to the new object instantiated

Var name = 'kaka '; Function Cat(){this.name = 'this '; This. type = 'this.type '; } var cat1 = new Cat(); console.log(cat1); // instantiate the new object Cat {name: "fish ", type:" Blue Cat "} console.log(cat1.name); / / a fishCopy the code

(4) When apply and call are invoked, this refers to the object in the parameter

Var name = 'I '; function eat(){ console.log(this.name); } var cat = {name:' year ',} var dog = {name:' year ',} eat. Call (cat); / / every year eat. Call (dog); / / goofyCopy the code

(5) Anonymous function call, pointing to the global object

Var name = 'kaka '; Var cat = {name:' fish ', eat (function(){console.log(this.name); // kaka})()} cat.eat;Copy the code

(six) timer call, pointing to the global variable

Var name = 'kaka '; Var cat = setInterval(function(){var name = 'I '; console.log(this.name); / / kaka clearInterval (cat); }, 500);Copy the code

Conclusion: This refers to the constructor call of the nearest object ③. This refers to the instantiated new object ④ Apply and call calls. This refers to the anonymous function call of the object ⑤ in the argument. This refers to a call to the global object Window ⑥ timer, and this refers to the global variable Window

5. The implementation principle and function of closures, several practical applications of closures in development can be listed

A package is a function that can read variables inside other functions and it’s useful for two things, one is that it can read variables inside functions, and the other is that it keeps the values of those variables in memory all the time.

function f1() { var n = 999; nAdd = function () { n += 1 } function f2() { alert(n); } return f2; } var result = f1(); result(); // 999 nAdd(); result(); / / 1000Copy the code

In this code, result is actually the closure f2 function. It runs twice, the first with a value of 999 and the second with a value of 1000. This proves that the local variable n in function f1 is kept in memory and is not automatically cleared after f1 is called. Why is that? The reason is that F1 is the parent of F2, and F2 is assigned to a global variable, which results in F2 always being in memory, and f2’s existence depends on F1, so F1 is always in memory and not collected by garbage collection when the call ends. NAdd =function(){n+=1}; nAdd is a global variable, not a local variable. Second, the value of nAdd is an anonymous function, and the anonymous function itself is a closure, so nAdd is a setter that operates outside the function on local variables inside the function.

6. Understand the principle of stack overflow and memory leak and how to prevent it

1, memory leakage: refers to the application of memory after execution is not timely clean up or destroy, occupy free memory, memory leakage too much, will lead to the following program can not apply for memory. Stack overflow: Indicates that the memory space has been used up and there is not enough memory available

A common approach is to set a variable to NULL and it will be collected by the next garbage collection mechanism. Common causes of memory leaks:

  • Memory leaks caused by global variables
  • closure
  • No timers are cleared

Solutions:

  • Reduce unnecessary global variables
  • Use closures strictly (because closures cause memory leaks)
  • Avoid endless loops

Enforcement mechanism

1. How does JavaScript implement asynchronous programming? Can you describe EventLoop in detail

In fact, there are two task queues, one is macro task queue and the other is micro task queue. When the main thread is executed, if there are micro tasks in the micro task queue, it will enter the execution stack first. When there are no tasks in the micro task queue, the macro task queue will be executed.

2. What are macro tasks and micro tasks

Microtasks include: native Promises (some implemented promises put then methods in macro tasks), Object.Observe (deprecated), MutationObserver, MessageChannel; Only when a promise calls then does the then function get pushed into the microtask. Macro tasks include: setTimeout, setInterval, setImmediate, I/O;

3. Implement serialization using Promise

function execute(tasks){ return tasks.reduce((previousPromise, currentPromise)=>previousPromise.then(resultList=>{ return new Promise(resolve=>{ currentPromise().then(result=>{ resolve(resultList.concat(result)) }).catch(()=>{ resolve(resultList.concat(null)) }) }) },Promise.resolve([]))) } const  execute = (tasks = []) => { const resultList = []; for(task of tasks){ try{ resultList.push(await tasks()) }catch(err){ resultList.push(null); } } return resultList; }Copy the code

4. Differences between Node and browser EventLoop

Before Node 10: Execute all tasks in a phase execute the nextTick queue and then execute the microtask queue. After Node 11: Consistent with browser behavior, execute the microtask queue every time a macro task executes.

Grammar and API

1. Understand the relationship between ECMAScript and JavaScript

The relationship between ECMAScript and JavaScript is that the former is a specification of the latter and the latter is an implementation of the former

2. SetInterval Points to pay attention to, use settimeout to achieve setInterval

function  mySetInterval(fn,mil){
    function interval(){
        setTimeout(interval,mil);
        fn();
    }
    setTimeout(interval,mil)
}
mySetInterval(function(){console.log(1)},1000)
Copy the code

3. What is anti-shake and throttling? What’s the difference? How to do that?

Buffeting Buffeting means that the function is executed only once in n time. If it is triggered multiple times in n time, the time will be recalculated

function debounce(fn){ let timeout =null; return function(){ clearTimeout(timeout); } function say(){console.log(' console.log ')} var myInput = function say(){console.log(' console.log ')} var myInput = document.getElementById('hello'); myInput.addEventListener('input',debounce(say))Copy the code

Throttling n is executed only once

function throttle(fn){ let canFlag = true; return function(){ if(! canFlag) return; canFlag = false; setTimeout(()=>{ fn.apply(this,arguments); CanFlag = true},1000)}} function say(){console.log(' throttle ',new Date())} var myInput = document.getElementById('hello'); myInput.addEventListener('input',throttle(say))Copy the code

4. Introduce the difference between Set, Map, WeakSet and WeakMap?

WeakSet structure is similar to Set, which is also a collection of non-repeating values. However, it differs from Set in two ways.

  • WeakSet members can only be objects, not other types of values
  • WeakSet objects are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet

WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs

  • WeakMap only accepts objects as key names (except null) and does not accept values of other types as key names
  • EakMap keys point to objects that are not counted in the garbage collection mechanism

HTML and CSS

HTML

1. Understand HTML from a normative perspective and use tags from a categorical and semantic perspective

2. Default styles, built-in attributes, differences between different browsers, and ways to deal with browser compatibility problems of common page tags

3. Purpose and configuration method of meta information tags (head, title, meta)

4.HTML5 offline cache principle

5. High performance animation can be drawn using Canvas API, SVG, etc

CSS

1.CSS box model, differences in different browsers

1. W3C standard box model: Properties width,height only contain content, not border and padding. 2. IE box model: Properties width,height contain border and padding, refer to content+padding+border. The CSS box model consists of content, padding, border, and margin. The size of the box is determined by the content+padding+border. The margin is the position of the box, not the size of the box. We should use the standard W3C model as much as possible when writing page code (DOCTYPE declaration in the page) to avoid multiple browsers’ incompatibility with the same page. Because if you don’t declare DOCTYPE, IE will interpret the box model as IE box model and FireFox will interpret it as W3C box model. If a DOCTYPE is declared on a page, all browsers interpret the box model as the W3C box model.

2. All CSS selectors and their priorities, usage scenarios, which can be inherited, and how to apply AT rules

3. What are CSS pseudo-classes and pseudo-elements? Their differences and practical applications

4.HTML document flow layout rules, CSS several positioning rules, positioning reference, the impact of the document flow, how to choose the best positioning way, Sprite diagram implementation principle

5. More than 6 horizontal and vertical schemes can be implemented and their advantages and disadvantages are compared

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <title>Document</title> <style>. Parent1 {width: 200px; height: 200px; background: red; position: relative; } .parent2{ display: table-cell; vertical-align: middle; text-align: center; } .parent5{ display: flex; align-items: center; justify-content: center; } .child1{ width: 100px; height: 100px; position: absolute; left: 50%; top:50%; margin-left: -50px; margin-top: -50px; line-height: 100px; text-align: center; } .child2{ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); } .child3{ position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; width: 100px; height: 100px; line-height: 100px; text-align: center; } .child4{ display: inline-block; width: 100px; height: 50px; overflow: scroll; } .child6{ width: 100px; height: 100px; display: inline-block; text-align: center; vertical-align: middle; line-height: 100px; } .parent6{ text-align: center; } .parent6::after{ content: ''; height: 100%; vertical-align: middle; display: inline-block; } </style> </head> <body> <p> </p> <div class="parent1"> <div class="child1">child1</div> </div> <p> Absolute +transform</p> <div class="parent1"> <div class="child2">child2</div> </div> Absolute +margin:auto</p> <div class="parent1"> <div class="child3">child3</div> </div> Table-cell vertical-align:middle</p> <div class="parent1 parent2"> <div class="child4"> Table-cell multi-line text vertically centered Table-cell vertical-align:middle</div> </div> Display :flex</p> <div class="parent1 parent5"> <div class="child5"> Flex </div> </div> </p> <div class="parent1 parent6"> <div class="child6"> </div> </body> </ HTML >Copy the code

6. Implementation principle of BFC, problems that can be solved, how to create BFC

Juejin. Cn/post / 684490…

7. CSS functions can be used to reuse code to achieve special effects

8. Master at least one PostCSS, Sass, and Less configuration

9.CSS modular scheme, how to configure loading on demand, how to prevent CSS blocking rendering

10. Familiar with CSS for common animations, such as gradients, movements, rotations, zooming, etc

11.CSS browser compatibility to understand the compatibility of different apis in different browsers

12. Master a complete responsive layout scheme

3. Computer fundamentals

Compilation principle

1. Understand what code is, and how does a computer turn it into a executable target program

Interpreted language (JS) is a kind of programming language. In this type of programming language, code is run sentence by sentence without the need for Compiled language, which is Compiled into machine code and then run as in Compiled language. This language requires an interpreter to dynamically interpret code into machine code at run time, or a subroutine that has been precompiled into machine code and then run.

2. Regular expression matching principle and performance optimization

3. How to parse JavaScript code into Abstract Syntax Trees (AST)

4. Coding principle of Base64

5. How to express and convert several base-conversion calculation methods in JavaScript

Network protocol

1. Understand what a protocol is, what constitutes the TCP/IP network protocol family, and what role each layer of protocol plays in an application program

2. Which protocols are reliable? What means does TCP have to ensure reliable delivery

3. Functions of DNS, detailed DNS resolution process, and DNS optimization principle

For example, the real domain name www.example.com is www.example.com.root, or www.example.com. Root is omitted because the root domain name is the same for all domain names.

The next level of the root domain is called a top-level domain (TLD), such as.com and.net. The next level is called a “second-level domain” (SLD), as in www.example.com. Example. At the next level are host names, such as the WWW in www.example.com, also known as “tertiary domain names”, which are assigned by users to servers in their own domains and can be assigned by users at will.

To summarize, the hierarchy of domain names is as follows.

Host name. secondary domain name. Top-level domain name Root domain nameCopy the code

To be clear, each level of domain name has its own NS record. The NS record points to the DNS server of the level of domain name. These servers know the various records of the next level of domain name.

Hierarchical search is to search NS records of domain names at each level from the root domain name to the final IP address. The process is as follows.

1. Query NS records and A records (IP address) of the TOP-LEVEL DNS server from the root DNS server. 2. Query the NS record and A record (IP address) of the secondary DNS server from the top-level DNS server. Get the IP address of "host name" from "secondary DNS"Copy the code

1. The network client is the computer we usually use. Open the browser and enter a domain name. For example, type www.163.com and your computer will send a DNS request to the local DNS server. The local DNS server is usually provided by your network access server provider, such as China Telecom and China Mobile.

2. Query the DNS request of www.163.com. After the DNS request reaches the local DNS server, the local DNS server queries its cache record first. If no, the local DNS server queries the DNS root server.

3. The root DNS server does not record the mapping between domain names and IP addresses. Instead, the root DNS server informs the local DNS server that you can query the IP address of the domain server.

4. The local DNS server continues to send requests to the domain server, which in this case is the.com domain server. After receiving the request, the.com domain server does not directly return the mapping between the domain name and IP address. Instead, it tells the local DNS server the address of the resolution server for your domain name.

5. In the end, the local DNS server to the domain name resolution server request, then will be able to receive a corresponding relationship between domain name and IP address, not only to the local DNS server IP address is returned to the user’s computer, and stored in the cache, the relation between arrange another time with other user query, can return the result directly, to speed up the network access.

4. Functions and principles of CDN

1. First, we type a url into the address bar. The browser finds that there is no DNS cache for this url, so it sends a request to the DNS server of the site.

2. The DNS server of the website has set CNAME, which points to a CDN server, namely ali Cloud, Tencent Cloud, Cloudflare, etc., to request the intelligent DNS load balancing system in THE CDN.

3. Load balancing The system parses domain names and returns the node with the fastest response to the user. Then the user sends a request to the node.

4. If it is the first time to access the content, the CDN server will request the data from the source station and cache it; otherwise, it will directly find the data in the cache node and send the request result to the user. Case without CNAME:

CNAME:

Can understand the meaning of common request headers. There are several request modes. What are the differences

6. The specific meanings of all HTTP status codes. You can quickly locate faults by viewing the abnormal status codes

7. Changes brought by HTTP1.1 and HTTP2.0

Juejin. Cn/post / 684490…

8. How do I enable HTTPS and hijack HTTPS requests

Juejin. Cn/post / 684490…

9. Understand the underlying principles of WebSocket and the differences between WebSocket and HTTP

Juejin. Cn/post / 684490… ### Design patterns

1. Proficient in using common front-end design patterns to write code, such as singleton pattern, decorator pattern, proxy pattern, etc

2. Similarities and differences between publish and subscribe mode and observer mode and their practical applications

3. Can say several design patterns in the development of practical application, understand the framework of the source code of the application of design patterns

4. Data structure and algorithm

JavaScript coding ability

1. Multiple ways to implement array de-weighting, flattening, comparing advantages and disadvantages

2. Multiple ways to achieve deep copy and compare the advantages and disadvantages

3. Handwriting function Currie function, and understand its application scenarios and advantages

4. Implement a sleep function

Manually implement the front wheels

1. Manually implement call, apply, and bind

Function.prototype.myCall = function (context = window,... args) { context.fn = this; console.log(args) let result = context.fn(... args); delete context.fn; return result; } Function.prototype.myApply = function (context = window, arr) { context.fn = this; let result = ! arr ? context.fn() : context.fn(... arr); delete context.fn; return result; } Function.prototype.myBind = function (context = window , ... arg) { context.fn = this; let bound = function () { let args = [...args].concat(... arguments); context.fn = this instanceof context.fn ? this : context; let result = context.fn(... args); delete context.fn; return result; } bound.prototype = new this(); return bound; }Copy the code

2. Manually implement Promise conforming to Promise/A+ specification and implement async await

function handlePromise(promise2, x, resolve, Reject){if (reject === x) {return reject(new TypeError('circular reference')); } if(x! ==null && (typeof x==='object' || typeof x ==='function')) { let called; // Called controls resolve or reject only once, multiple calls have no effect. try{ let then = x.then; if(typeof then === 'function') { then.call(x,y=>{ if(called) return; called = true; handlePromise(promise2,y,resolve,reject) },r => { if(called) return; called = true; reject(r); }) } else { reject(x); } }catch(err) { if (called) return; called = true; reject(err); } } else { reject(x); } } class Promise { constructor(executor){ this.status = 'pending'; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; let resolve = (value) => { if(this.status === 'pending') { this.value = value; this.status = 'resolved'; this.onResolvedCallbacks.foEach(fn => fn(this.value)); } } let reject = (reason) => { if(this.status === 'pending') { this.reason = reason; this.status = 'rejected'; this.onRejectedCallbacks.foEach(fn => fn(this.reason)); } } try{ executor(resolve,reject) }catch(err){ reject(err); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : y => y; onRejected = typeof onRejected === 'function' ? onRejected : err => {throw err} let promise2; / / return the new promise if (this. The status = = = 'pending') {this. OnResolvedCallbacks. Push () promise2 = new Promise((resolve,reject)=>{ this.onResolvedCallbacks.push(()=>{ setTimeout(()=>{ try{ let x = onFulfilled(this.value); handlePromise(promise2,x,resolve,reject) }catch(err){ reject(err); } },0) }) this.onRejectedCallbacks.push(()=>{ setTimeout(()=>{ try{ let x = onRejected(this.reason); handlePromise(promise2,x,resolve,reject) }catch(err){ reject(err); } },0) }) }) } if (this.status === 'resolved') { promise2 = new Promise((resolve,reject) =>{ setTimeout(()=>{ try{ let x  =onFulfilled(this.value); handlePromise(promise2,x,resolve,reject) }catch(err){ reject(err); } },0) }) } if(this.status === 'rejected') { onRejected(this.reason); promise2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ try{ let x = onRejected(this.reason); handlePromise(promise2,x,resolve,reject) }catch(err){ reject(err); } },0) }) } return promise2; } catch(onRejected){return this. Then (null,onRejected); Promise.all = function (promiseArrs) {// Add an all method to the Promise class, Return new promise ((resolve, reject) => {// Return a new promise let arr = []; Let I = 0; Function handleData(index, data) {arr[index] = data; i++; If (I === promisearrs.length) {resolve(arr); if (I === promisearrs.length) {resolve(arr); }} for (let I = 0; i < promiseArrs.length; I ++) {// Loop over promiseArrs[I]. Then ((data) => {handleData(I, data); // pass the result and index into the handleData function}, reject)}})} promise. race = function (promises) {return Promise((resolve, resolve) reject) => { for (let i = 0; i < promises.length; i++) { promises[i].then(resolve, reject); } }) } Promise.resolve = function (val) { return new Promise((resolve, reject) => resolve(val)); } Promise.reject = function (val) { return new Promise((resolve, reject) => reject(val)); } module.exports = Promise;Copy the code

3. Write an EventEmitter to implement event publishing and subscription

class EventEmitter { constructor(){ this.events = {} } on(eventName,callback){ if(this.events[eventName]){ this.events[eventName].push(callback) } else{ this.events[eventName] = [callback] } } emit(eventName,... rest){ if(this.events[eventName]){ this.events[eventName].forEach(fn=>fn.apply(this,rest)) } } } const event =new EventEmitter(); const handle = (... Log (pyload) event.on('click',handle) event.emit('click',1,2,3)Copy the code

4. There are two ways to implement bidirectional binding, which can be implemented manually

5. Write json. stringify, json. parse

JSON = {parse: function (STR) {return eval('(' + STR + ')') // function (str) { if (typeof str === 'number') { return Number(str); } if (typeof str === 'string') { return str }; var s = ''; console.log(Object.prototype.toString.call(str)) switch (Object.prototype.toString.call(str)) { case '[object Array]': s += '['; for (var i = 0; i < str.length - 1;  i++) { if (typeof str === 'string') { s += '"' + str[i] + '",' } else { s += str[i] + ',' } } if (typeof str[str.length  - 1] == 'string') { s += '"' + str[i] + '"' } else { if (str[str.length - 1] == null) { str[str.length - 1] = null;  s += 'null'; } else { s += (str[str.length - 1] ? str[str.length - 1] : '') } } s += "]"; break; case '[object Date]': console.log(str.toJSON()) s+='"'+(str.toJSON? str.toJSON():str.toString())+'"'; break; case '[object Function]': s= 'undefined'; break case '[object Object]': s+='{' for(var key in str) { if(str[key] === undefined){ continue; } if(typeof str[key] === 'symbol' || typeof str[key] === 'function') { continue; } if(typeof Object.prototype.toString.call(str[key]) === '[object RegExp]') { continue; } s+=('"'+key+'":"'+str[key]+'",') } s = s.slice(0,s.length-1); if(s===''){s+='{'} s+='}' break } return s; }}Copy the code

6. Write a template engine and explain how it works

7. Handwriting lazy loading, pull down refresh, pull up loading, preloading and other effects

The data structure

1. Understand the characteristics of common data structures and their strengths and weaknesses when used in different scenarios

2. Understand the storage principles of arrays and strings, and skillfully apply them to solve problems

3. Understand the basic structure and characteristics of binary tree, stack, queue and hash table, and can apply it to solve problems

4. Understand the basic structure and usage scenarios of graphs and heaps

algorithm

1. Calculate the time and space complexity of an algorithm, and estimate the time and memory consumption of business logic code

2. At least understand the implementation principles, application scenarios, advantages and disadvantages of five sorting algorithms, and can quickly tell the time and space complexity

3. Understand the advantages and disadvantages of recursion and loop, application scenarios, and be able to skillfully apply them in development

4. Can apply backtracking algorithm, greedy algorithm, divide-and-conquer algorithm, dynamic programming and other complex problems

5. Front-end algorithm scheme for processing massive data

Five, operating environment

The browser API

1. W3C compliant DOM manipulation apis, browser differences, and compatibility provided by browsers

2. All global apis, browser differences, and compatibility provided by the Browser Object Model (BOM)

3. Performance optimization for massive DOM operations, massive data (merge operations, Diff, requestAnimationFrame, etc.)

4. Store massive data for the browser and optimize operation performance

5. Specific implementation mechanism of DOM event flow, differences of different browsers, event proxy

6. Several ways for the front-end to initiate network requests and their underlying implementation, can write native Ajax and FETCH, and can skillfully use third-party libraries

7. Same-origin policy of browser, how to avoid same-origin policy, similarities and differences of several methods, and how to select the type

8. Several storage mechanisms provided by browsers, advantages and disadvantages, and the right choice in development

9. Browsers communicate across tabs

Principles of browsers

1. The JavaScript engines used by each browser, their similarities and differences, and how to distinguish them in code

2. Request data to the end of the request several times with the server interaction

TCP three-way handshake: 1. The client sends a SYN packet to the server and waits for the server to confirm receipt. 2. The server acknowledges the syn packet received from the client and sends a SYN + ACK packet to the client. 3. The client confirms to receive the SYN + ACK packet from the server and sends the ACK packet to the server. After establishing a connection with the server, the TCP three-way handshake is completed. Question 1: Why is there a three-way handshake when connecting, but a four-way handshake when closing?

A: After receiving a SYN request packet from the Client, the Server sends a SYN+ACK packet. ACK packets are used for reply, and SYN packets are used for synchronization. However, when the Server receives a FIN packet, the SOCKET may not be closed immediately. Therefore, the Server can only reply with an ACK packet to tell the Client, “I received the FIN packet you sent.” I can send FIN packets only after all packets on the Server are sent. Therefore, THE FIN packets cannot be sent together. Therefore, a four-step handshake is required.

【 QUESTION 2】 Why does the TIME_WAIT state take 2MSL to return to CLOSE?

A: Although it is reasonable that all four packets are sent and we can directly enter the CLOSE state, we must pretend that the network is unreliable and the last ACK can be lost. Therefore, the TIME_WAIT state is used to resend ACK packets that may be lost. The Client sends the last ACK reply, but the ACK may be lost. If the Server does not receive an ACK, it repeatedly sends FIN fragments. Therefore, the Client cannot shut down immediately. It must confirm that the Server received the ACK. The Client enters the TIME_WAIT state after sending an ACK. The Client sets a timer and waits for 2MSL of time. If a FIN is received again within that time, the Client resends the ACK and waits for another 2MSL. The so-called 2MSL is twice the MSL(Maximum Segment Lifetime). MSL refers to the maximum lifetime of a fragment in the network. 2MSL refers to the maximum time required for a send and a reply. If the Client does not receive a FIN again until 2MSL, the Client concludes that the ACK has been successfully received and terminates the TCP connection.

Question 3. Why can’t we use two handshakes to connect?

A: The 3-way handshake performs two important functions, both by preparing the parties to send the data (both parties know that they are ready) and by allowing the parties to negotiate the initial serial number, which is sent and confirmed during the handshake.

Now instead of three handshakes requiring only two handshakes, deadlocks can occur. As an example, consider the communication between computers S and C. Suppose C sends A connection request packet to S, which receives the packet and sends an acknowledgement reply packet. Following the two-handshake protocol, S considers that the connection has been successfully established and can start sending packets of data. However, in the case that THE reply packet of S is lost in transmission, C will not know whether S is ready, do not know what sequence number S establishes, and C even doubts whether S has received its connection request packet. In this case, C considers that the connection has not been established successfully, and ignores any data sent by S, and only waits for the connection to confirm and reply the grouping. S repeatedly sends the same packet after the sent packet times out. This creates a deadlock.Copy the code

[Q4] What if the connection has been established, but the client suddenly fails?

TCP also has a keepalive timer, so obviously if the client fails, the server can’t wait forever and waste resources. The server resets this timer every time it receives a request from the client, usually for two hours. If it does not receive any data from the client within two hours, the server sends a probe segment, which is then sent every 75 seconds. If there is no response after 10 probe packets are sent, the server assumes that the client is faulty and closes the connection.

3. Describe the detailed process from entering the URL to displaying the page

4. Principle of browser parsing HTML code and process of building DOM tree

5. How does the browser parse CSS rules and apply them to the DOM tree

6. How do browsers draw parsed DOM trees with styles

7. How to configure asynchronous resource loading based on the operating mechanism of the browser

8. The underlying principle of browser backflow and redraw, the cause and how to effectively avoid it

When the size, structure, or attributes of some or all of the elements in the Render Tree change, the process by which the browser rerenders some or all of the document is called reflux. Operations that cause backflow:

  • Page first render
  • The browser window size changed. Procedure
  • The size or position of the element changed
  • Element content changes (number of words or image size, etc.)
  • Element font size changes
  • Add or remove visible DOM elements
  • Activate CSS pseudo-classes (such as: :hover)
  • Query some properties or call some methods

When a change in the style of an element in a page does not affect its position in the document flow (e.g., color, background-color, visibility, etc.), the browser assigns the new style to the element and redraws it, a process called redraw. CSS

  • Avoid table layouts.
  • Change the class at the very end of the DOM tree whenever possible.
  • Avoid setting multiple inline styles.
  • Apply the animation to an element whose position attribute is absolute or fixed.
  • Avoid USING CSS expressions (such as calc()).

JavaScript

  • To avoid manipulating styles too often, it is best to override the style property once, or define the style list as class and change the class property once.
  • To avoid frequent DOM manipulation, create a documentFragment, apply all DOM manipulation to it, and finally add it to the document.
  • You can also set display: None to the element and display it after the operation is complete. Because DOM operations on elements with the display attribute none do not cause backflow and redraw.
  • Avoid frequently reading properties that cause backflow/redraw, and if you do need to use them more than once, cache them in a variable.
  • Use absolute positioning on elements with complex animations to keep them out of the document stream, which would otherwise cause frequent backflow of parent elements and subsequent elements.
  • 9. Browser garbage collection mechanism, how to avoid memory leakage

Principles of the garbage collection mechanism The garbage collector periodically finds variables that are no longer in use, and then frees the memory occupied by them.

What is a variable that is no longer in use?

Variables that are no longer used, i.e. end-of-life variables, are local variables. Local variables exist only during the execution of a function. When the function is finished and there are no other references (closures), the variable is marked for recycling.

The lifetime of global variables does not end until the browser unloads the page, meaning that global variables are not garbage collected.

Working principle:

When a variable enters the environment (such as declaring a variable in a function), it is marked as “into the environment” and as “out of the environment” when it leaves the environment. Those marked “out of the environment” reclaim memory.

Workflow:

  1. The garbage collector will mark all variables stored in memory at runtime.
  2. Untag variables in the environment and variables referenced by variables in the environment.
  3. Variables that still have tags are considered to be ready for deletion.
  4. Finally, the garbage collector performs the final step of memory cleaning, destroying the tagged values and reclaiming the memory they occupy.

As of 2008,IE, Chorme, Fireofx, Safari, and Opera all use a marked sweep garbage collection strategy, but at different intervals

Ways to avoid memory leaks

  • Use fewer global variables to avoid accidental global variables
  • Be careful with closures and clean up references to Dom elements.
  • Destroy the callbacks in the timer when they don’t work.
  • To avoid forgetting caused by negligence, we can use WeakSet and WeakMap structures, whose references to values are not included in the garbage collection mechanism, indicating that they are weak references.

Here’s an example:

const wm = new WeakMap();
const element = document.getElementById('example');
wm.set(element, 'some information');
wm.get(element) // "some information"
Copy the code

In the case of copying code, once the reference to the node is removed, its memory is freed by the garbage collection mechanism. The key value pair saved by Weakmap will also disappear automatically.

####10. How to select and control the cache scheme adopted by the browserCache process analysisThe browser communicates with the server in reply mode, that is, the browser initiates an HTTP request and the server responds to the request. After the browser sends the request to the server for the first time and gets the request result, it decides whether to cache the result or not according to the cache identifier of the HTTP header in the response packet. If yes, the request result and cache identifier are stored in the browser cache. The simple process is as follows:From the figure above, we can know:

  • Each time the browser initiates a request, it first looks up the result of the request and the cache identifier in the browser cache

  • Each time the browser receives the result of the returned request, it stores the result and the cache id in the browser cache

    The above two conclusions are the key to the browser cache mechanism, which ensures that each request is cached and read. As long as we understand the rules of the browser cache, all problems will be solved, and this article will analyze this in detail. To help you understand, we have divided the caching process into two parts, namely mandatory caching and negotiated caching, depending on whether the HTTP request needs to be re-initiated to the server.

Mandatory cache

Forced caching refers to the process of searching the browser cache for the request result and deciding whether to use the cached result based on the cache rule of the result. There are three main cases of forced caching (the negotiation cache process is not analyzed for the moment), as follows:

  • If the cache result and cache id do not exist and the cache is forced to be invalid, the request is directly sent to the server (the same as the first request), as shown below:

  • The cache result and cache id exist, but the result is invalid and the cache is forced to become invalid. In this case, the negotiated cache is used (not analyzed), as shown in the following figure

  • If the cache result and cache id exist and the cache result is not invalid, the cache is forced to take effect and the cache result is directly returned, as shown in the following figure

When the browser sends a request to the server, the server returns the Cache rule in the HTTP header of the HTTP response packet together with the request result to the browser. The fields that Control the mandatory Cache are Expires and cache-Control, respectively. Cache-control has a higher priority than Expires.ExpiresExpires is a field that HTTP/1.0 controls the web cache. Its value is the expiration time that the server returns to the cache of the result of the request. That is, when the client initiates the request again, if the time is less than the Expires value, the cached result is used directly.Cache-ControlIn HTTP/1.1, cache-control is the most important rule, which is mainly used to Control web caching. Its main values are:

  • Public: All content will be cached (both client and proxy can be cached)

  • Private: All content can be cached only by the client. The default value of cache-control

  • No-cache: indicates the contents of the client cache, but whether to use the cache is verified by the negotiated cache

  • No-store: All content is not cached, that is, neither mandatory cache nor negotiated cache is used

  • Max-age = XXX (XXX is numeric) : The cache contents will expire after XXX seconds

With HTTP/1.1, Expire was replaced by cache-control. The reason is that Expires caching works by comparing the client time with the time returned by the server. If one side of the client and server is not accurate), the forced cache will be invalidated, so the existence of the forced cache will be meaningless.

Because cache-Control has a priority over Expires, cache-Control values are cached directly, meaning that if the request is made again within 600 seconds, the cached result will be used to enforce the Cache.

Note: Cache-control is a better option than Expires in cases where you can’t determine whether the client’s time is synchronized with the server’s, so only cache-Control works when both exist.

Where does the browser cache reside, and how do I determine if the mandatory cache is in effect in the browser?

  • From memory cache: The memory cache has two characteristics, namely fast access and timeliness:

Fast read: The memory cache directly stores the compiled and parsed files into the memory of the process, occupying certain memory resources of the process, and facilitating the fast read of the next run. Timeliness: Once the process is shut down, its memory is emptied.

  • From disk cache: The cache is directly written to the disk file. To read the cache, I/O operations are performed on the disk file stored in the cache and the cache content is parsed again. The reading of the cache is complex and slower than that of the memory cache.

In the browser, js and image files are directly stored in the memory cache after being parsed. Therefore, when refreshing the page, you only need to read from the memory cache directly. CSS files are stored in disk files, so every rendering page needs to be read from disk cache.

Negotiate the cache

Negotiation cache is a process in which the browser sends a request to the server with the cache ID after the cache is invalid, and the server decides whether to use the cache based on the cache ID. There are two main situations:

  • The negotiation cache takes effect and 304 is returned as follows

  • Negotiation cache invalid, return 200 and request result as follows

Similarly, the identity of the negotiation cache is returned to the browser in the HTTP header of the response packet together with the request result. The fields controlling the negotiation cache are as follows: Last-modified/if-modified-since and Etag/if-none-match, where Etag/if-none-match has a higher priority than last-modified/if-modified-since.Last-Modified / If-Modified-Since

  • Last-modified returns the time when the resource file was Last Modified on the server when the server responds to the request, as shown below.

  • If-modified-since indicates that when the client initiates the request again, it carries the last-Modified value returned from the Last request and tells the server the Last Modified time of the resource returned from the Last request. After receiving the request, the server finds that the request header contains the if-Modified-since field. The server compares the value of the if-Modified-since field with the last modification time of the resource on the server. If the last modification time of the resource on the server is greater than the value of the if-Modified-since field, the server compares the value of the if-Modified-since field with the last modification time of the resource on the server. The resource is returned with the status code of 200. Otherwise, 304 is returned, indicating that the resource has not been updated. You can continue to use the cache file, as shown below.

  • Etag is a unique identifier (generated by the server) that is returned to the current resource file when the server responds to a request, as shown below.

  • If-none-match indicates that when the client initiates the request again, it carries the unique Etag value returned by the last request. The value of this field tells the server the unique Etag value returned by the last request. After receiving the request, the server finds that the request header contains if-none-match. The server compares the if-none-match field with the Etag value of the resource on the server. If the value is consistent, 304 is returned, indicating that the resource is not updated. If no, return the resource file with the status code 200, as shown in the following figure.

#### summary Mandatory caches take precedence over negotiated caches. If mandatory caches (Expires and cache-control) are in effect, they are used directly. If it does not take effect, the negotiation cache (last-modified/if-modified-since and Etag/if-none-match) is carried out. The negotiation cache is determined by the server whether to use the cache. If the negotiation cache is invalid, then the cache of the request is invalid and the request result is obtained again. Store it in the browser cache; If it takes effect, 304 is returned and the cache continues to be used. The main process is as follows:Reference Documents:www.cnblogs.com/chenhuichao…

Node

1. Understand the role of Node in the application, you can use Node to build a front-end running environment, use Node to operate files, operate databases, etc

2. Master a Node development framework such as Express, Express and Koa

3. Familiar with the API provided by Node, such as Path, Http and Child Process, and understand the implementation principle

4. The underlying operating principle of Node and the similarities and differences between it and the browser

5. Implementation principle of Node event-driven and non-blocking mechanism

Frameworks and class libraries

TypeScript

1. Understand object-oriented concepts such as generics and interfaces, and TypeScript’s implementation of object-oriented concepts

2. Understand the benefits of working with TypeScript and understand the basic TypeScript syntax

3.TypeScript rule detection

4. You can develop with TypeScript in React, Vue, etc

React

1.React and VUE selection, advantages and disadvantages, and core architecture differences

2. How to effectively manage the setState execution mechanism in React

3.React event implementation mechanism

4. Internal implementation of React virtual DOM and Diff algorithm

5. What problems does React Fiber solve

6. The React Router and Vue Router are implemented based on the underlying principles and dynamic loading principles

7. Familiar with React API, lifecycle, etc., able to use HOC, Render props, Hooks and other high-level usages to solve problems

8. Based on the React features and principles, you can manually implement a simple React

Vue

1. Why do I write a key in a list component when I write React/Vue?

Without keys and using simple templates, nodes can be reused more effectively based on this premise. Diff speed is also faster without keys, because it takes time to add and delete nodes with keys. This is what the VUE documentation calls the default mode. However, this is not the function of the key, but the node can be reused in the absence of a key to improve performance. This mode has some hidden side effects, such as the possibility that transitions may not occur, or that there is bound data (form) state at some nodes and state mismatches occur. The VUE documentation also explains this. In addition, the function of key is to find the corresponding node faster during the execution of diFF algorithm and improve the speed of DIFF

The key attribute is used in Vue's virtual DOM algorithm to identify VNodes when comparing old and new nodes. If keys are not used, Vue uses an algorithm that minimizes dynamic elements and tries to repair/reuse the same type of elements as much as possible. With a key, it rearranges elements based on the change in the key and removes elements where the key does not exist. Child elements that have the same parent must have a unique key. Duplicate keys cause render errors. When making dynamic changes, try not to use index as the loop key. If you use index as the key, then when deleting the second item, index will change from 1,2, 3 to 1,2 (instead of 1,3), and still cause update errors.Copy the code

The problem without Key value is shown in the figure below. The old set contains nodes A, B, C and D, while the updated new set contains nodes B, A, D and C. At this point, the new and old sets make diff difference comparison and find that B! = A, create and insert B into new set, delete old set A; Similarly, create and insert A, D, and C, and delete B, C, and D.

React finds that such operations are cumbersome and redundant. These nodes are the same, but their positions change, requiring complex and inefficient deletion and creation operations. In fact, you only need to move the positions of these nodes. React proposes an optimization strategy that allows developers to add unique keys to subnodes of the same hierarchy. Even though this is a small change, it makes a huge difference in performance.

React/Vue Diff uses the Key to find that the nodes in the old and new sets are the same nodes. Therefore, there is no need to delete or create nodes, only need to move the nodes in the old set. The diff result given by React is as follows: B and D do nothing, while A and C move. So how does such an efficient diff work? In simple terms, there are the following steps: 1. Traverse the nodes of the new set, and determine whether there are the same nodes in the new and old sets through the unique key. 2. If the same node exists, move the node. Before moving the node, compare the position of the current node in the old set with that of lastIndex.

This is a sequential optimization method. LastIndex is constantly updated, indicating that the visited node is at the right-most position (i.e., the largest position) in the old set. If the currently visited node in the new set is larger than lastIndex, it means that the currently visited node is lower in the old set than the last node. This node does not affect the position of other nodes, so it does not need to be added to the difference queue, that is, it does not need to be moved. Only when the accessed node is smaller than lastIndex, it needs to be moved. Here's an example of a whole diagram.Copy the code

As shown in the figure above, using the new tree as the baseline for the loop:

B’s subscript in the old set is BIndex=1, so lastIndex=0, so lastIndex < BIndex, nothing is done, Max (BIndex, lastIndex) A =0, lastIndex=1, lastIndex > AIndex, Max (AIndex, lastIndex) D in the old set is DIndex=3, and lastIndex=1. Max (DIndex, lastIndex) C = CIndex=2, lastIndex=3, LastIndex > CIndex, we need to move the C in the old tree to the index lastIndex, and the value lastIndex= math.max (CIndex, lastIndex) because C is already the last node, so the Diff ends here. There is no key update problem

Delete the second input box, but the page still retains the second input box content flow as follows:

And since 1 doesn’t change, we’re going to reuse in place and since 2 becomes 3, we’re going to reuse in place. The data/state attribute of the descendant element is not affected by the change of 2 to 3. If 3 is lost, then all descendant elements are deleted

2. Advantages of virtual DOM and DIff algorithm

Benefits of the virtual DOM

The virtual DOM was designed to address browser performance issues. For example, if there are 10 DOM updates in one operation, the virtual DOM does not immediately manipulate the DOM. Instead, the virtual DOM stores the diff content of the 10 updates to a local JS object, and finally attches the JS object to the DOM tree for subsequent operations. Avoid lots of unnecessary calculations. Therefore, the advantage of using JS object to simulate DOM node is that the update of the page can be reflected in THE JS object (virtual DOM), and the speed of the JS object operation in memory is obviously faster. After the completion of the update, the final JS object is mapped into the real DOM and submitted to the browser to draw.The Diff operation

In real code, a deep traversal of the old and new trees would take place, with a tag for each node. Each time a node is traversed, the node is compared to the new tree, and any differences are recorded in an object. Let’s create a new tree and compare it to the previous one to see how the Diff algorithm works. Flat layer Diff, only the following four cases:

1. The node type is changed, for example, P is changed to H3 in the figure below. We call this process REPLACE. Unload the old node and load the new node directly. The old node will be unloaded, including the children below. This is not efficient if the new node is only of different type from the old node, but all the children below are the same. But it’s worth it to avoid order n^3 time. This also reminds developers to avoid unnecessary node type changes, such as changing div to P at run time makes no sense.

2. The node type is the same, only the attribute or attribute value is changed. We call this process PROPS. Instead of triggering node unload and load, node update is triggered. 3. The Text has changed. The Text pair is also a Text Node, which is relatively simple. Move/add/remove child nodes, a process we call REORDER. For example, add an F node between BC and B of nodes A, B, C, D, and E.

Our simple and brutal approach is to traverse each node of the new virtual DOM and compare it with the corresponding node of the old virtual DOM. If there is any difference in the old DOM, uninstall the original and press the new one. This will operate on every node after F. Load C, load F, load D, load C, load E, load D, load E. The efficiency is too low

If we add a key to an array or enumeration element in JSX, it can directly find the specific location to operate according to the key, which is relatively efficient. Levenshtein Distance algorithm can be used to realize the common minimum editing Distance problem, and the time complexity is O(M*N). However, we usually only need some simple movement to meet the needs, and reduce the accuracy to O(Max (M,N)).

The development of diverse

1. Principle, advantages and disadvantages of single page application (SPA), and master a scheme for rapid development of SPA

2. Understand the principle and usage of Viewport, EM and REM, as well as the difference and practical application of resolution, PX, PPI, DPI and DP

3. Mobile terminal page adaptation solutions and adaptation solutions for different models

4. Master a JavaScript mobile client development technology, such as React Native: Can build React Native development environment, be skilled in development, understand the operation principle of React Native, and adapt to different terminals

5. Master a JavaScript PC client development technology, such as Electron: able to set up the Electron development environment, be skilled in development, and understand the operation principle of Electron

6. Master a small program development framework or native small program development

7. Understand the internal implementation principle of multi-terminal framework, and understand the use of at least one multi-terminal framework

Data Flow management

1. Master the traditional cross-component communication solutions of React and Vue, and compare the differences and similarities between the data flow management framework

2. Proficient in using Redux to manage data flow, and understand its implementation principle and middleware implementation principle

3. What are the advantages of using Mobx to manage data flow and understand how it works compared to Redux

4. Proficient in using Vuex to manage data flow and understand its implementation principle

5. Similarities and differences, advantages and disadvantages of the above data flow schemes, and technical selection under different circumstances

Seven, front-end engineering

The project build

1. Understand the difference between NPM and YARN dependency package management

Yarn is a new NPM client that has been redesigned to allow developers to do all the necessary operations in parallel, and some other improvements have been added. The speed has been significantly improved, and the overall installation time has become less like NPM, where YARN uses local caching. Unlike NPM, YARN does not require an Internet connection to install local cache dependencies and provides offline mode. This feature was proposed in the NPM project in 2012, but never implemented. A license to merge all packages used in the project

2. You can use NPM to run custom scripts

3. Understand the role of tools like Babel, ESLint, WebPack, etc

4.ESLint rule detection principle, commonly used ESLint configuration

5. The core principle of Babel, you can write a Babel plug-in

Like a compiler, Babel’s translation process is divided into three stages:

Parse parses code into an abstract syntax tree (AST), which is how computers understand our code (extensions: In general, each JS engine has its own AST, such as v8, where Chrome converts JS source code to abstract syntax trees, which in turn convert to bytecode or machine code), while Babel is implemented via Babylon. In simple terms, it is a compilation process for JS code, a process of lexical analysis and grammar analysis.

Perform a series of transformations on the AST. Babel receives the AST and traverses it with babel-traverse, adding, updating, and removing the AST.

Convert the transformed AST into JS code, using the module babel-generator. The Babel-core module combines the three to simplify the API provided externally.

6. A front-end code compatibility scheme, such as Polyfill, can be configured

7. Compilation principle, construction process, hot update principle, difference and application of Chunk, bundle and Module of Webpack

8. Skilled in configuring existing loaders and plugins to solve problems, and able to write loaders and plugins by myself

nginx

1. Features and examples of forward and reverse proxies

2. Can manually build a simple nginx server,

3. Proficient in the application of common nginx built-in variables and the writing of common matching rules

4. Nginx can be used to achieve request filtering, configure GZIP, load balancing, etc., and can explain its internal principle

Viii. Projects and Business

Performance optimization

1. Understand front-end performance measurement indicators, performance monitoring points, and a front-end performance monitoring scheme

2. Familiar with common Web and App performance optimization schemes

3.SEO ranking rules, SEO optimization schemes, and SEO with front and back end separation

4.SSR implementation scheme, advantages and disadvantages, and performance optimization

5. Performance optimization scheme of Webpack

6.Canvas performance optimization scheme

7.React, Vue and other frameworks use performance optimization solutions

The front security

1.XSS attack principle, classification, specific cases, and front-end defense

Cross-site scripting is an attack that runs illegal HTML tags or JavaScript in the browser of a registered user of a Web site with a security vulnerability. The principle of XSS is that malicious attackers insert malicious executable Web script codes into Web pages. When users browse the page, the script codes embedded in the Web will be executed, so that attackers can steal user information or other purposes of violating users’ security and privacy.

1. Non-persistent XSS (Reflective XSS)

Non-persistent XSS vulnerability attacks have the following characteristics:

  • Real-time, no server storage, direct HTTP GET and POST requests can complete an attack, GET user privacy data.
  • The attacker needs to trick clicks, which must be initiated by the user clicking on the link
  • The feedback rate is low, so it is difficult to find and respond to repair
  • Steal sensitive confidential information from users

To prevent non-persistent XSS vulnerabilities, you need to ensure a few things:

  • All content rendered or rendered data for a Web page must come from the server.
  • Try not to render directly from DOM apis such as URLS, document.referrer, document.forms, etc.
  • Do not use eval, new Function(), document.write(), document.writeln(), window.setinterval (), window.settimeout (), innerHTML, Methods such as document.createElement() that execute strings.

Failing that, you must also escape the string arguments passed in by methods involving DOM rendering. The front-end rendering will need to do escape encoding for any field

2. Persistent XSS (storage XSS) Persistent XSS vulnerability, generally exists in Form submission and other interactive functions, such as article message, text information submission, etc. Hackers take advantage of the XSS vulnerability to submit the content to the database for persistent storage through normal functions. When the front end page gets the injection code that the back end reads from the database, it just renders it for execution

The following conditions must be met for a successful attack:

  • POST request to submit the form without escaping it directly into the library.
  • The back-end retrieves data from the database without escaping it and outputs it directly to the front-end.
  • The front-end takes the back-end data and renders it directly into the DOM without escaping it.

Persistent XSS has the following characteristics:

  • Persistence, embedded in the database
  • Steal user sensitive private information
  • WeiHaiMian widely

CSP is essentially a whitelist, where the developer explicitly tells the browser which external resources can be loaded and executed. We just need to configure the rules, how to intercept is up to the browser implementation. We can minimize XSS attacks in this way.

CSP can usually be turned on in two ways:

  • Set content-security-policy in the HTTP Header
  • How to set the meta tag

2) Escape characters The user’s input can never be trusted. The most common way to escape input and output is to escape quotes, Angle brackets, and slash

3) HttpOnly Cookie this is the most effective defense against XSS attacks to steal user cookies. When Web applications set cookies, their attribute is set to HttpOnly, which can prevent the cookies of the Web page from being stolen by malicious JavaScript and protect the user’s cookie information.

2.CSRF attack principle, specific cases, and front-end defense

1. Principle of CSRF attack Three conditions must be met to complete a CSRF attack:

  • The user has logged in to site A and logged the cookie locally
  • Without logging out of site A (that is, when the cookie is in effect), the user visits site B, which is A lure hazard provided by A malicious attacker (site B requires access to site A).
  • Site A does not do any CSRF defense

2. You can follow the following rules to defend against CSRF attacks:

  • Get requests do not modify the data
  • Do not allow third-party websites to access user cookies
  • Prevents third party websites from requesting interfaces
  • The request is accompanied by authentication information, such as a captcha or Token

1) SameSite can set the SameSite property for cookies. This property indicates that cookies are not sent along with cross-domain requests and can greatly reduce CSRF attacks, but this property is not currently compatible with all browsers.

HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP Referer Check HTTP You can defend against CSRF attacks by checking the source of the request. The referer of normal requests has certain rules. For example, the referer of submitted forms must be the request initiated on the page. Therefore, by checking whether the HTTP header referer value is the page, we can determine whether it is a CSRF attack.

But in some cases, such as a jump from HTTPS to HTTP, the browser will not send the referer for security reasons, and the server will not be able to check. If other sites in the same domain have XSS vulnerabilities, attackers can inject malicious scripts into other sites, and victims can also be attacked if they access such sites. For the above reasons, Referer Check cannot be completely relied on as the main means of CSRF defense. However, the occurrence of CSRF attacks can be monitored through the Referer Check.

3) Anti-CSRF Token At present, a relatively perfect solution is to add anti-CSRF Token. A request is sent with a randomly generated token in the form of a parameter in the HTTP request, and an interceptor is set up on the server to verify the token. The server reads the token value in the cookie of the current domain of the browser and checks whether the token value in the request and the cookie exist and are equal. Then the server considers the request to be a valid request. Otherwise, the request will be considered illegal and the service will be rejected.

This method is much safer than the Referer check. Tokens can be generated after the user logs in and put into session or cookie, and then the server takes the tokens out of session or cookie at each request and compares them with the tokens in this request. Because of the token, the attacker cannot construct a complete URL to carry out CSRF attack. However, when multiple pages coexist, when a page consumes the token, the forms on other pages still retain the consumed token, and token errors occur when forms on other pages are submitted.

3. Principles and defense measures of HTTP hijacking and page hijacking

Principle of click hijacking After logging in the system of website A, the user is tempted to open the third-party website by the attacker, and the third-party website introduces the page content of website A through iframe. When the user clicks A button (decorated button) in the third-party website, it actually clicks the button of website A.

X-frame-options x-frame-options is an HTTP response header that is well supported in modern browsers. The HTTP response header is designed to defend against clickjacking attacks nested with iframe.

The response header has three optional values, respectively

  • DENY: indicates that the page is not allowed to be displayed in iframe mode
  • SAMEORIGIN, which means pages can be displayed under the same domain name using an IFrame
  • Allow-from: indicates that the page can be displayed in the iframe of the specified source

2) JavaScript defense For some ancient browsers, the above method was not supported, so we have to use JS to prevent click hijacking.

if(top.location ! = self.location){ top.location = self.location; }Copy the code

Ix. Resource recommendation

Language foundation

  • [📚] JavaScript high-level programming (must-see) : book.douban.com/subject/105…

  • [📚] high-performance JavaScript:book.douban.com/subject/536…

  • Modern JavaScript tutorial: zh.javascript.info/

  • ECMAScript 6 tutorial: es6.ruanyifeng.com/

  • ECMAScript 6 standard: www.ecma-international.org/ecma-262/6….

  • Use HTML meta tags summary and attribute is introduced: segmentfault.com/a/119000000…

  • CSS coding guide: github.com/chadluo/CSS…

Computer Fundamentals

  • Big front end developers need to understand the compilation principle and the basis of language knowledge: fullstack. Blog / 2017/06/24 /…

  • The illustration HTTP:book.douban.com/subject/258…

  • [📚] JavaScript design patterns and development practices: book.douban.com/subject/263…

  • Regular Expressions: Link.juejin. Im /? Target = HTTP…

Data structures and algorithms

  • The beauty of the data structure and algorithm: time.geekbang.org/column/intr…

  • Animation of the LeetCode problem: github.com/MisterBooo/…

  • JavaScript data structures and algorithms: github.com/ConardLi/aw…

  • 30-seconds-of-code (there is a lot of JS code in it that is very clever and I am translating it into Chinese) : github.com/ConardLi/30…

Runtime environment

  • Browser principle passages in the front end of heavy science: time.geekbang.org/column/arti…

  • The basic principle of graphical browsers: zhuanlan.zhihu.com/p/47407398

  • 7 Days to learn NodeJS: github.com/nqdeng/7-da…

  • Node. Js module loading and operation principle: efe.baidu.com/blog/nodejs…

Frameworks and class libraries

  • The TypeScript faced: zhongsp. Gitbooks. IO/TypeScript -…

  • The React. Js books: huziketang. Mangojuice. Top/books/React…

  • React In-depth series: Juejin. Im/Post /5cad39…

  • IO /react-webpa/fakefish.github…

  • Vue. Js technology revealed: github.com/ustbhuangyi…

  • Vuex- Managing state in Vue: sabe. IO /tutorials/g…

  • Do you need Mobx or Redux? : juejin. Im/post / 5 a7fd7…

  • The Underscore the source code analysis: yoyoyohamapi. Gitbooks. IO/undersercor…

  • Wechat applets development resources summary: github.com/justjavac/a…

  • Tencent Mobile Web front-end knowledge base: github.com/AlloyTeam/M…

The front-end engineering

  • A (long) know babel:zhuanlan.zhihu.com/p/43249121 gas

  • Webpack fool guide: zhuanlan.zhihu.com/p/20367175

  • Webpack principle: segmentfault.com/a/119000001…

  • Liao Xuefeng git tutorial: www.liaoxuefeng.com/wiki/001373…

  • Graphic Git: marklodato. Making. IO/visual – Git -…

  • Nginx: Juejin. Im /post/5c85a6…

  • Continuous integration using Jenkins: www.liaoxuefeng.com/article/001…

Projects and Business

  • Common six Web security analysis: github.com/ljianshu/Bl…

  • In-depth understanding of front-end performance monitoring: Juejin. Im /post/ 5CAaAC…

  • [📚] high-performance website construction guidelines: book.douban.com/subject/313…

  • How to quickly integrate into the technical strength of the front-end team: Juejin. Im /post/ 5CB860…

Learning promotion

  • Imprint Chinese (various Chinese development documents) : www.docschina.org/

  • Front-end learning methods: github.com/helloqingfe…

  • How to achieve continuous technical growth in and out of work: Juejin. Im/Post / 5CBd74…

  • Good front-end blogging round-up: github.com/foru17/fron…

I also recommend the personal blogs of several big guys that I have been following:

  • Hu Yu’s blog: github.com/mqyqingfeng…

  • Zhang Xinxu blog: www.zhangxinxu.com/wordpress/

  • Left ear mouse: coolshell.cn/

Besides the technology

  • Terms of the Internet: www.jianshu.com/p/9a7ca206c…

  • The Internet communication, q&a, learning the art of: zhuanlan.zhihu.com/p/41431775

  • Often work overtime into the night, how to keep healthy: www.zhihu.com/question/21…