preface

Most of the content of the article is to make a summary of some knowledge points, not everything, for some specific implementation steps and the underlying principle of the code will not be posted, otherwise the length is too long

But don’t worry, the detailed explanation of the relevant knowledge points will post links for your reference, these are bloggers usually write notes and read some excellent blog posts, hope to help you check the gaps, comb your front-end knowledge system ~

Mark: Yes, it is.

First, HTML basics

1. What is the function of docType?

  • DOCTYPE is the HTML5 standard web page declaration and must be declared on the first line of an HTML document. To tell the browser’s parser what standard document to use to parse the document. Different rendering modes can affect how the browser interprets CSS code and even JavaScript scripts.

What is the difference between HTML, XHTML, and XML?

  • HTML(Hypertext Markup Language): Before HTML4.0, THERE were implementations and standards for HTML, which made HTML very confusing and loose
  • XML(Extensible Markup Language): Primarily used to store data and structures, JSON is similar but lighter and more efficient
  • XHTML(Extensible Hypertext Markup Language): Based on the above two

3, HTML semantic understanding?

  • Semantic: Refers to the use of appropriate semantic HTML tags, such as header tags for the header, article tags for the body, etc
  • Benefits: Improved readability and SEO optimization

4, Common meta tags?

  • Charset, which describes the encoding of an HTML document
<meta charset="UTF-8" >
Copy the code
  • Http-equiv, the equivalent of HTTP headers, such as the following code to set HTTP cache expiration dates
The < meta - equiv = HTTP"expires" content="Wed, 20 Jun 2019 22:33:00 GMT">Copy the code
  • Viewport: Controls the size and proportion of the viewport
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
Copy the code

5. What is the difference between defer and async in script tags?

  • Defer: The script will not be executed immediately after it has been asynchronously loaded, but after the document has been parsed.
  • Async: executes immediately after the script is loaded

6. Front-end storage mode?

  • Cookies: good compatibility, request header with cookies is convenient, the disadvantage is that the size is only 4K, automatic request header to add cookies waste traffic, each domain limit 20 cookies, it is troublesome to use the need to self-encapsulation
  • LocalStorage: HTML5 to join the key-value pair (key-value) as the standard, the advantage is easy to operate, permanent storage (unless manually deleted), the size of 5M, compatible with IE8+
  • SessionStorage: basically similar to localStorage, the difference is that sessionStorage will be cleaned up after the page is closed, and different from cookie and localStorage, it can not be shared in all the same source Windows, is the session level storage mode
  • IndexedDB: NoSQL database, stored in key-value pairs for quick reading, ideal for Web scenarios and easy to use in JavaScript.

Second, the CSS

1. CSS box model

Standard model: Width and height calculation does not include padding and border; Through the box – sizing: content – box; To set (browser default).

IE model: width and height calculation includes padding and border; Through the box – sizing: border – box; To set up.

2. BFC (Block Formatting Context)

Features:

  • Is a separate container, the elements inside and outside do not affect each other;
  • BFC vertical margins overlap;
  • The BFC region does not overlap with the floating element region;
  • When calculating the height of the BFC, the floating element is also involved.

Creation method:

  • Float is not none;
  • The value of position cannot be static or relative;
  • Display inline-box, table, table-cell, etc.
  • The overflow is not visible

Function:

  • Remove the floating
  • Prevent overlapping margins between adjacent elements in the same BFC container

3, achieve vertical center layout

  • Wide high fixed
div.parent {
    position: relative; 
}

div.child {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
或
div.child {
    width: 100px;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

Copy the code
  • The width and height are not fixed
div.parent { display: flex; justify-content: center; align-items: center; } or div. The parent {display: flex; } div.child{ margin:auto; } or div.parent {position: relative; } div.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } or div.parent {display: grid; } div.child { justify-self: center; align-self: center; }Copy the code

More layout types refer to: Dry goods! All kinds of common layout + well-known site instance analysis

4, the advantages and disadvantages of opacity: 0, visibility: hidden, display: none and applicable scenarios are compared.

  • Structurally: display: None disappears from the render tree, elements take up no space and are unclickable; Visibility: Hidden does not disappear from the render tree, and elements continue to occupy space but cannot be clicked; Opacity: 0 does not disappear from the rendering tree, and elements occupy space and are clickable.
  • Heritability: display: none and opacity: 0 are non-inherited properties; The parent element is set to display: None or opacity: 0, while the child element cannot be displayed no matter how it is set. Visibility: hidden will be inherited by the quilt element, and the child element can be set to visibility: visible; To unhide.
  • Performance: display: None Causes rearrangement and consumes high performance. Visibility: Hidden will cause redrawing, with relatively small performance consumption; Opacity: 0 rebuilds layers and has high performance

5. The difference between link tags and import tags

  • Link is an HTML tag, while @import is provided by CSS.
  • When the page is loaded, link is loaded at the same time, while the CSS referenced by @import is loaded after the page is loaded.
  • Link style has a higher weight than @import;
  • Link can be dynamically imported using JS, @import cannot;
  • Link This has no compatibility requirements, while @import requires IE5 to be recognized.

6. Solution to mobile Retina 1px pixel problem

  • viewport + rem
  • background-image
  • Pseudo-element + transform Scale ()
  • box-shadow

Read more: 7 Ways to Fix the 1px border on mobile Retina Screens

7, text display line number control

  • A single
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
Copy the code
  • Multiple lines
overflow: hidden; text-overflow: ellipsis; // Out of display'... 'display: -webkit-box; // Display elements as elastic stretchable box models. -webkit-line-clamp: 2; // To limit the number of lines of text displayed in a block element -webkit-box-orient: vertical; // Sets or retrieves the arrangement of the children of the flex box objectCopy the code

8. Clear the floating mode

1、
.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: ""; clear: both; height: 0; } 2, clear:both 3, overflow:hiddenCopy the code

9. What is the difference between Transition and animate?

  • Transition: Used for transition effects, no frame concept, only start and end states, low performance overhead
  • Animate: Used for animation, the concept of frames, can be repeatedly triggered and have intermediate states, high performance overhead

10. Implement a sector

.sector {
  width: 0;
  height: 0;
  border-width: 50px;
  border-style: solid;
  border-color: red transparent transparent;
  border-radius: 50px;
}
Copy the code

Three, JS

1. Built-in types of JS

  • Basic types: null, undefined, Boolean, number, string, symbol
  • Object: Reference type

NaN is also of type number and is not equal to itself.

2. Type judgment

  • Typeof
console.log(typeof 1);                  // number
console.log(typeof 'a');                // string
console.log(typeof true);               // boolean
console.log(typeof undefined);          // undefined
console.log(typeof function fn() {}); //function
console.log(typeof {});                 // object
console.log(typeof null);               // object
console.log(typeof []);                 // object
console.log(typeof new Error());        // object
Copy the code

For basic types, all but null will display the correct type; For objects, all except functions display Object

  • Object.prototype.toString
var number = 1;             // [object Number]
var string = '123';         // [object String]
var boolean = true;         // [object Boolean]
var und = undefined;        // [object Undefined]
var nul = null;             // [object Null]
var obj = {a: 1}            // [object Object]
var array = [1, 2, 3];      // [object Array]
var date = new Date();      // [object Date]
var error = new Error();    // [object Error]
var reg = /a/g;             // [object RegExp]
var func = function a() {}; // [object Function]function checkType() {
    for (var i = 0; i < arguments.length; i++) {
        console.log(Object.prototype.toString.call(arguments[i]))
    }
}

checkType(number, string, boolean, und, nul, obj, array, date, error, reg, func)
Copy the code

Read more: JavaScript is New when It comes to Typing

3. Understanding of prototypes and prototype chains

  • Prototype: Each function has the Prototype attribute, which points to the prototype object; The advantage of using a prototype object is that all object instances share the properties and methods it contains.
  • Prototype chain: mainly solves the problem of inheritance; Each object has a prototype object, which is referred to by a __proto__ pointer and inherits methods and properties from it, while the prototype object may also have a prototype, layer by layer, eventually pointing to NULL.
  • The following diagram shows the relationship between constructors, stereotype objects, instances, and stereotype chains:

Read more: JavaScript Is New when You Look at the Past — Prototypes and prototype chains

4. Execution context

  • Global execution context
  • Function execution context
  • Eval Execution context

Read more: JavaScript is New — execution environment and scope

5, closures

  • Closures are functions that have access to variables in the scope of another function.
  • Closures can cause variables inside a function to be stored in memory, which can cause a lot of memory overhead, so don’t abuse closures. The solution is to set unused local variables to NULL before exiting the function;

Classic interview question: Modify the following code to output 0-9

for (var i = 0; i< 10; i++){
	setTimeout(() => { console.log(i); }, 1000)} Method 1setThe third argument to the Timeout function is passed as the first argument to the callback functionfor (var i = 0; i < 10; i++) {
  setTimeout(i => { console.log(i); }, 1000, I)letProperties of variablesfor (let i = 0; i < 10; i++) {
  setTimeout(() => { console.log(i); }, 1000)} is equivalent tofor (let i = 0; i < 10; i++) {
  let_i = i; // const _i = i;setTimeout(() => { console.log(_i); }, 1000)} Method 3, use the function self-execution mode, the currentforThe I is passed in during the loop, building up the block-level scope.for (var i = 0; i < 10; i++) {
  (i => {
    setTimeout(() => {
      console.log(i);
    }, 1000)
  })(i)
}
Copy the code

6. This points to the problem

The direction of this depends on which way the function is called:

  • Function call: non-strictly this refers to a global object, strictly undefined
  • Function call: This refers to the object calling the function
  • Constructor call: this refers to the instance object created by new
  • Call () and apply: Their first argument is a reference to this

4 ways to call a function

  • Added: this in the arrow function
function a() {
    return() = > {return () => {
        	console.log(this)
        }
    }
}
console.log(a()()())
Copy the code

The arrow function does not have this. The this in this function depends only on the this of the first function outside it that is not the arrow function. In this case, because calling a matches the first case in the previous code, this is the window. And once this is bound to the context, it will not be changed by any code.

7. Implementation of Call and apply

Function.prototype.call2 = function(context) {
    var context = context || window;
    context.fn = this;

    var args = [];
    for(var i = 1, len = arguments.length; i < len; i++) {
        args.push('arguments[' + i + '] ');
    }
    
    var result = eval('context.fn(' + args + ') ');
    
    delete context.fn
    return result;
}

Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if(! arr) { result = context.fn(); }else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + '] ');
        }
        result = eval('context.fn(' + args + ') ')
    }

    delete context.fn
    return result;
}
Copy the code

Implementation details can be found in JavaScript: Call () and apply() implementations

8. Implementation of BIND

Function.prototype.bind2 = function (context) {

    if(typeof this ! = ="function") {
      throw new TypeError("error"); } var self = this; var args = Array.prototype.slice.call(arguments, 1); Var fNOP = // Make a transition through an empty function to avoid modifying the prototype properties of the binding functionfunction () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}
Copy the code

The bind() method is implemented in JavaScript

9. Implementation principle of New

What does the new operator do?

  • Create an empty object
  • Then make the empty object’s __proto__ point to the function’s prototype
  • Execute the code in the constructor, where this refers to the object
  • If the constructor has a return value, that object is used as the return value. If there is no return or a primitive type is returned, the new object is returned as the value
function objectFactory() {

    var obj = new Object(),

    Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;

};
Copy the code

Implementation details can be found in JavaScript: the implementation of the new operator

9. Implementation of Instanceof

functionInstance_of (L, R) {//L stands for left expression, R stands for right expression var O = r.protoType; // take the display prototype of R L = l.__proto__; // take the implicit prototype of Lwhile (true) {
    if (L === null) return false;
    if(O === L) // Key here: return if O is strictly Ltrue
      return true; L = L.__proto__; }}Copy the code

10, depth copy

  • Shallow copy – If the elements of the copied object are primitive, a copy is made without affecting each other. If the elements of the copied object are objects or arrays, only the references to the objects and arrays are copied. In this case, changes between the old and new objects will affect each other.
// Shallow copies of arrays: slice(), concat() // Shallow copies of objects: object.assign (), ES6 extension operatorsCopy the code
  • Deep copy – A complete copy of an object. Even if the objects are nested, the two objects are separated from each other. Modifying the properties of one object does not affect the other.
// Recursive implementationfunction clone(source) {
    var target = {};
    for(var i in source) {
        if (source.hasOwnProperty(i)) {
            if (typeof source[i] === 'object') {
                target[i] = clone(source[i]); // If it is a reference type, continue traversing}else {
                target[i] = source[i]; }}}return target;
}
Copy the code

Of course, this is just a simple implementation, and does not take into account special cases such as functions in objects or arrays, and special types of copies such as re.

// JSON.parse(JSON.stringify)
var arr = [
   { value: 1 },
   { value: 2 },
   { value: 3 }
];
var copyArr = JSON.parse(JSON.stringify(arr))
copyArr[0].value = 0;
console.log(arr);       // [{value: 1}, { value: 2 }, { value: 3 }]
console.log(copyArr);   // [{value: 0}, { value: 2 }, { value: 3 }]
Copy the code

The above method is simple and crude, but the disadvantage is that you cannot copy the function.

For more details on deep copy implementation, see: The Ultimate Quest for deep Copy (90% of people don’t know)

11. Realization of anti-shake and throttling (simple version)

  • Anti-shake: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated
Funtion debounce(fn) {// Create a token to store the return value of the timerlet timeout = null;
    return function() {// Cancel the previous delayed call method clearTimeout(timeout) each time the event is raised; // Create a new onesetTimeout, which guarantees that the fn function Timeout = will not be executed if triggered repeatedly within 1000mssetTimeout(() => {
            fn.apply(this, arguments);
        }, 1000);
    };
}
Copy the code
  • Throttling: A high-frequency event fires, but only executes once in n seconds, so throttling dilutes the execution frequency of the function
functionThrottle (fn) {// Save a token through a closurelet canRun = true;
    return function(){// Each time the function is executed, the flag is checked firsttrue, not fortruereturn
        if(! canRun)return; // After the last timer was executed, canRun istrue, so set it tofalse
        canRun = false;
        setTimeout(() => { fn.apply(this, arguments); / / in at lastsetAfter Timeout completes, set the flag totrue(Key) indicates that the next loop is ready to execute. The flag is always when the timer is not executedfalse, at the beginning byreturnOff canRun =true; }}}, 1000)Copy the code

Implementation of ES5 inheritance

// Combinatorial inheritancefunction SuperType(name) {
    this.name = name;
    this.colors = ['red'.'blue'.'green'];
}
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.constructor = SubType;

SubType.prototype.sayAge = function() {
    console.log(this.age);
}
Copy the code

13. Development history, advantages and disadvantages of JS asynchronous solution

  • Callback function
ajax('XXX1', () => {// Callback function body ajax()'XXX2', () => {// Callback function body ajax()'XXX3', () => {// callback function body})})Copy the code

Advantages: Solves the synchronization problem

Cons: Callback hell, no try catch, no return

  • Promise
ajax('XXX1'). Then (res => {// operation logicreturn ajax('XXX2'}). Then (res => {// operation logicreturn ajax('XXX3'}). Then (res => {// operation logic})Copy the code

Pros: Solved the callback hell problem

Disadvantages: Promise cannot be cancelled and errors need to be caught through callback functions

  • Generator
function *fetch() {
    yield ajax('XXX1', () => {})
    yield ajax('XXX2', () => {})
    yield ajax('XXX3', () => {})}let it = fetch()
let result1 = it.next()
let result2 = it.next()
letResult3 = it.next() // Use const co = require('co')

function *fetch() {
    yield ajax('XXX1', () => {})
    yield ajax('XXX2', () => {})
    yield ajax('XXX3', () => {})
}

co(fetch()).then(data => {
    //code
}).fetch(err => {
    //code
})

Copy the code

Advantages: can control the execution of the function, with the automatic actuator CO module to simplify the steps of manual execution

Disadvantages: Not with the CO function library, it is more troublesome to use

  • async/await
// Async is a syntactic sugar, which is implemented by wrapping Generator functions and automatic actuators (CO) in a function asyncfunction test() {// If the following code does not have a dependency, it can use promise.all.'XXX1')
  await fetch('XXX2')
  await fetch('XXX3')}read().then((data) => {
    //code
}).catch(err => {
    //code
});

Copy the code

Pros: The code is clear, doesn’t have to write a bunch of then chains like Promise, and handles callback hell

Disadvantages: await transforms asynchronous code into synchronous code, and using await results in performance degradation if multiple asynchronous operations have no dependencies.

14, setTimeout, Promise, Async/Await distinction

For this problem, we should first understand the JS Event Loop mechanism. We recommend that you read this article first: This time, thoroughly understand the JavaScript execution mechanism

  • SetTimeout – The setTimeout callback is placed in the macro task queue and executed after the stack is empty
console.log('script start'//1. Print script startsetTimeout(function() {
    console.log('settimeout') // 4. Print setTimeout}) // 2. callsetThe Timeout function and define the callback function console.log('script end'Script start->script end->settimeoutCopy the code
  • Promise — The Promise itself is a synchronous execute now function. When resolve or reject is executed in an executor, then/catch is executed asynchronously. When the main stack is complete, The resolve/reject method is invoked.
console.log('script start')
let promise1 = new Promise(function (resolve) {
    console.log('promise1')
    resolve()
    console.log('promise1 end')
}).then(function () {
    console.log('promise2')})setTimeout(function() {
    console.log('settimeout')
})
console.log('script end'Script start->promise1->promise1 end->script end->promise2-> setTimeoutCopy the code
  • Async /await – an async function returns a Promise object, and when the function executes, it returns an await and waits until the triggered asynchronous operation is complete before executing the following statement in the function body. It can be understood as giving up the thread, out of the async function body.
async function async1() {
   console.log('async1 start');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}

console.log('script start');
async1();
console.log('script end'Async1 start->async2->script end->async1 endCopy the code

15. Simple implementation of Promise

Use of Promise (please refer to Teacher Ruan Yifeng’s ES6 document for detailed use of Promise)

var promise = new Promise((resolve,reject) => {
    ifResolve (value)}else {
        reject(error)
    }
})
promise.then(function (value) {
    // success
},function (value) {
    // failure
})
Copy the code

Simple implementation

function myPromise(constructor) {
    let self = this;
    self.status = "pending"Self. value = undefined; Self. reason = undefined; // Define the state of the rejected statefunction resolve(value) {
       if(self.status === "pending") {
          self.value = value;
          self.status = "resolved"; }}function reject(reason) {
       if(self.status === "pending") {
          self.reason = reason;
          self.status = "rejected"; Constructor (resolve,reject); } catch(e) { reject(e); }}Copy the code

Add then method

myPromise.prototype.then = function(onFullfilled,onRejected) {
   let self = this;
   switch(self.status) {
      case "resolved":
        onFullfilled(self.value);
        break;
      case "rejected":
        onRejected(self.reason);
        break;
      default:       
   }
}

var p = new myPromise(function(resolve,reject) {
    resolve(1)
});
p.then(function(x) {
    console.log(x) // 1
})
Copy the code

For more details on the Promise principle, I recommend the Promise implementation principle (source code attached). This article is very detailed and easy to understand.

16. Development history of front-end modularization

  • IIFE: Use self-executing functions to write modularity, features: execute code in a separate function scope, avoiding variable conflicts.
(function() {return {
	data:[]
  }
})()
Copy the code
  • AMD: Write modularity using requireJS. Dependencies must be declared in advance.
define('./index.js'.function(code){// code is what index.js returns})Copy the code
  • CMD: use seaJS to write modularity, features: for dependent modules is delayed execution, dependency can be written nearby, wait until the dependency is needed to introduce the dependency, support dynamic import dependency file.
define(function(require, exports, module) {  
  var indexCode = require('./index.js');
});
Copy the code
  • CommonJS: built-in modularity in NodeJS.
var fs = require('fs');
Copy the code
  • ES Modules: Modularity introduced in ES6, supports import to import another JS.
import a from 'a';
Copy the code

17. What are the differences between ES6 modules and CommonJS modules?

  • ES6 module at compile time, can determine module dependencies, and input and output variables; CommonJS module, loaded at runtime.
  • The ES6 module automatically adopts strict mode, regardless of whether “Use strict” is written in the module header.
  • Require can be dynamically loaded. Import statements cannot. Import statements must be in the top-level scope.
  • In ES6 modules, the top-level this refers to undefined, and in CommonJS modules, the top-level this refers to the current module.
  • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.

Fourth, network foundation

1. Main features of HTTP protocol

  • Simple, fast, flexible, connectionless, stateless

2. Components of HTTP packets

  • Request message:
    • Request line (HTTP method + page address + HTTP protocol + version)
    • Request header (key + value value)
    • Empty lines (empty lines that the server uses to determine that the next part of the request is no longer the header, but is parsed as the request body)
    • Request body (data part)
  • Response message: status line + response header + blank line + response body

3. HTTP method

  • GET => Obtain resources
  • POST => Transfer resources
  • PUT => Updates resources
  • DELETE => DELETE resources
  • HEAD => Obtain the packet header

4. The difference between POST and GET

  • GET is harmless when the browser falls back, while POST resubmits the request *
  • GET requests are actively cached by browsers, whereas POST is not, unless manually set *
  • GET request parameters are retained in the browser’s history, while POST parameters are not
  • A GET request has a length limit on the parameters it passes in the URL, whereas a POST request has no length limit
  • The GET argument is passed through the URL, and the POST is placed in the Request body *
  • GET requests can only be url encoded, while POST supports multiple encoding methods
  • The URL generated by GET can be bookmarked, but POST cannot
  • GET accepts only ASCII characters for the data type of the argument, while POST has no restrictions
  • GET is less secure than POST because parameters are exposed directly to the URL and therefore cannot be used to pass sensitive information

5. HTTP status code

  • 1XX: Indicating message – indicating that the request has been accepted and processing continues

  • 2xx: Success: The request has been accepted successfully

    • 200: OK: indicates that the request from the client is processed correctly on the server
    • 204: No content: indicates that the request is successful, but the response packet does not contain the body of the entity
    • 205: Reset Content: indicates that the request is successful, but the response packet does not contain the body part of the entity. Different from 204 response, the requestor is required to Reset the Content
    • 206: Partial Content, a client sends a GET request with a Range header, and the server completes it (for example, requesting a larger file, such as a vedie or audio tag for playback of audio and video addresses)
  • 3xx: Redirect – Further action must be taken to complete the request

    • 301: Moved permanently, permanently redirects, indicating that the resource has been assigned a new URL
    • 302: Found, temporary redirection, indicates that the resource has been assigned a new URL temporarily
    • 303: see Other: indicates that another URL exists for the resource and you need to use the GET method to obtain the resource
    • 304: Not Modified: indicates that the server allows access to the resource, but the request condition is not met
    • 301: temporary redirect, similar to 302, but expects the client to keep the request method the same and send the request to the new address
  • 4XX: Client error – The request has a syntax error or the request cannot be implemented

    • 400: bad Request: Syntax errors exist in the request packet
    • 401: Unauthorized: Indicates that the request to be sent requires authentication information authenticated through HTTP
    • 403: forbidden: Indicates that the access to requested resources is denied by the server
    • 404: Not found: The requested resource was not found on the server
  • 5xx: Server error — the server failed to fulfill a valid request

    • 500: Internal sever Error: an error occurred when the server executed the request
    • 501: Not Implemented: the server does Not support a function that is required for the current request
    • 503: Service unavailable: Indicates that the server is temporarily overloaded or is down for maintenance and cannot process requests

6. TCP three-way handshake and four-way wave

Three handshakes and four waves can simulate a walkie-talkie conversation

  • Three handshakes:
A: Hello, this is B: Roger that, this is B: Ok, we are ready to talkCopy the code
  • Four waves:
A: I have no more to say. I have one last thing to say. B: I have finished.Copy the code

For more details, see: Interviews — Network TCP/IP

7, HTTPS

HTTPS still transmits information over HTTP, but the information is encrypted over the TLS protocol.

Encryption in TLS:

  • Symmetric encryption – both sides have the same secret key and both sides know how to encrypt and decrypt the ciphertext.
  • Asymmetric encryption – there are public key and private key, the public key owner can know, the data can be encrypted with the public key, but the data must be decrypted with the private key, the private key is only known to the party distributing the public key.

HTTPS handshake process:

  • In the first step, the Client provides the protocol version number, a Client random number generated by the Client, and the encryption method supported by the Client.
  • In the second step, the Server confirms the encryption method used by both parties and presents the digital certificate and a server-generated Server random number.
  • Third, the client verifies that the digital certificate is valid, then generates a new random number (Premaster Secret), encrypts this random number using the public key in the digital certificate, and sends it to the server.
  • Fourth, the server uses its own private key to obtain the random number sent by the client (Premaster secret).
  • Fifth step, the client and server use the first three random numbers to generate session keys according to the agreed encryption method, which are used to encrypt the whole process of the following conversation.

7. HTTP 2.0 features

  • Binary transmission: Divide all transmitted information into smaller messages and frames and encode them in binary format
  • Multiplexing: Multiple requests can be sent in a TCP connection
  • The Header compression
  • Server push: The server can push additional resources to the client without an explicit request from the client

Http1.0 http1.1 Http2.0 features and differences

8, the user enters the URL to the page rendering process

  • User input URL
  • Domain name Resolution (DNS Resolution)
  • After the IP address is found, a TCP three-way handshake is established to establish a connection with the target server
  • After the handshake is complete, the browser sends an HTTP request to the target host using the specified protocol (HTTP)
  • The server processes the received request and returns the data to the browser
  • The browser received the HTTP response packet. Procedure
  • Close the connection browser to parse the document
  • Read page content, browser rendering, parsing HTML source code
  • Generate Dom trees, parse CSS styles, and interact with JS
  • During the Render tree generation, the browser starts to invoke GPU rendering, compose layers, and display the content on the screen

Browsers and Web security

1. Event mechanism

  • There are three stages of event triggering:
Capture phase -- Window propagates to event trigger, target phase is triggered when registered capture event is encountered -- registration event bubble phase is triggered when propagated to event trigger, window propagates from event trigger, registered bubbling event is encounteredCopy the code
  • The specific flow of capturing DOM events:
Window object => Document object => HTML tag => Body tag =>... => Target element (bubble vice versa)Copy the code
  • Common uses of the Event object
Event. The preventDefault () / / prevents the default event, such as a tag of the jump behavior event. StopPropagation () / / stop the bubbling event. StopImmediatePropagation () / / incident response priorities: For example, when the same element is bound to different events, event A is triggered to prevent event B from triggering event.currenttarget // The element of the currently bound eventCopy the code

2, cross-domain

Same-origin policy:

  • In this case, Ajax requests cannot be sent, cookies, LocalStorage, and IndexDB cannot be obtained, and DOM cannot be obtained.

Several cross-domain solutions:

  • Json – using<script>Tags have no cross-domain limiting features through<script>The tag points to an address that needs to be accessed and provides a callback function to receive data.
<script src="http://domain/api? param1=a&param2=b&callback=jsonp"></script>
<script>
    function jsonp(data) {
    	console.log(data)
	}
</script>
Copy the code

Encapsulate a JSONP method

function jsonp({url, params, cb}) {
    returnNew Promise((resolve, reject) => {// Create a script taglet script = document.createElement('script'); // Attach the callback function to window[cb] =function(data) { resolve(data); / / code execution, delete the insert script tags. The document body. RemoveChild (script). } // the callback function is added to the request address params = {... params, cb}let arrs = [];
        for(let key in params) {
            arrs.push(`${key}=${params[key]}`);
        }
        script.src = `${url}?${arrs.join('&')}`; document.body.appendChild(script); }); } / / usefunction sayHi(data) {
    console.log(data);
}
jsonp({
    url: 'http://localhost:3000/say',
    params: {
        //code
    },
    cb: 'sayHi'
}).then(data => {
    console.log(data);
});
Copy the code
  • CORS — Server SettingsAccess-Control-Allow-OriginYou can turn on CORS. This attribute indicates which domain names can access resources. If a wildcard is set, all websites can access resources.
  • Document.domain — only for the same second level domain name, e.ga.test.comandb.test.com, just add to the pagedocument.domain = 'test.com'Indicates that the same secondary domain name can be implemented across domains.
  • PostMessage – new cross-domain communication method in H5, such as window A(http:A.com) sending messages to window B(http:B.com)
Send data in A
window.postMessage('data'.'http://B.com');
Listen in window B
window.addEventListener('message'.function(event){
    console.log(event.origin);
    console.log(event.source);
    console.log(event.data);
}, false)
Copy the code
  • Hash: The part of the URL that follows the ‘#’. Changes to the Hash page are not refreshed
# Usage scenario: when page A is embedded in cross-domain page B via iframe or frame
# code in A:
var B = document.getElementByTagName('iframe');
B.src = B.src + The '#' + 'data';
# code in B:
window.onhashchange = function () {
    var data = window.location.hash;
}
Copy the code

3. Rendering mechanics

  • Browser rendering process:
    • Process THE HTML and build the DOM tree
    • Build a CSS rule tree
    • Combine the DOM tree with the CSS rule tree into a render tree
    • According to the layout of the render tree, calculate the position of each node
    • Call THE GPU to draw, synthesize the layer and display it on the screen

  • Repaint and Reflow
    • Redraw – When a node needs to change its appearance without affecting the layout, such as changing color
    • Backflow – Layout or geometry properties need to be changed
  • When redraw and backflow occur (Backflow must occur redraw, redraw does not necessarily cause backflow.)
    • Add or remove visible DOM elements
    • The position of the element changes
    • The size of the element changes (including margins, inner borders, border size, height, width, etc.)
    • Content changes, such as text changes or an image being replaced by another image of a different size.
    • Browser window size changes (because backflow calculates element position and size based on viewport size)
  • Reduce redrawing and reflow
    • Use translate instead of top
    • Use visibility instead of display: None, because the former will only cause redraw and the latter will cause backflow (changing the layout)
    • Take the DOM offline and modify it, for example: first give the DOM to display: None (once Reflow), then you modify it 100 times before displaying it
    • Do not place DOM node property values in a loop as variables in the loop
    • Do not use the table layout, it is possible that a small change will cause the entire table to be rearranged
    • The choice of animation speed, the faster the animation speed, the more backflow times, can also choose to userequestAnimationFrame
    • CSS selectors match from right to left to avoid DOM depth
    • Turn frequently running animations into layers that prevent backflow from affecting other elements. For the video TAB, for example, the browser automatically turns the node into a layer.

Redraw and Redraw for more details: Do you really understand redraw and redraw

4. Browser caching

The principle of caching – the requested resources are stored in the local disk, and the next resource is read directly from the disk instead of sending requests to the server.

Cache classification:

  • Strong caching – implemented with two types of response headers:ExpiresCache-Control. Strong caching means that no request is required during caching, with a state code of 200
Expires: Wed, 22 Oct 2018 08:41:00 GMT // Expires is an artifact of HTTP / 1.0, indicating that the resource Expires after Wed, 22 Oct 2018 08:41:00 GMT and needs to be requested again. // Expires is limited to local time. If you change the local time, the cache may be invalidated. Cache-control: max-age=30 // Cache-control occurs in HTTP / 1.1 and takes precedence over Expires. This attribute indicates that the resource will expire after 30 seconds and needs to be requested again.Copy the code
  • Negotiated cache – If the cache expires, we can use the negotiated cache to resolve the problem. Negotiation cache requires a request, and 304 is returned if the cache is valid. The negotiated cache needs to be implemented by both the client and the server
    • Last-ModifiedIf-Modified-Since— indicates the last modification date of the local file,If-Modified-SincewillLast-ModifiedIs sent to the server, asking the server if the resource has been updated since that date, and sending the new resource back if it has been updated. (However, if the cache file is opened locally, it will causeLast-ModifiedHas been modified so it appears in HTTP / 1.1ETag).
    • ETagIf-None-MatchETagIt’s like a fingerprint on a file,If-None-MatchWill the currentETagSend to the server to ask for the resourceETagIf there is a change, send the new resource back. andETagPriority thanLast-Modified

To learn more about the browser caching mechanism, see: Understand the Browser caching mechanism in depth.

5. Web security

XSS

  • Basic concept: XSS, also known as cross-domain scripting, also known as Cross-site Scripting
  • How to attack: Attack a site by injecting malicious tags or JS code into pages.
  • How to defend against: making maliciously inserted tags or JS code unexecutable, such as escaping input and output content

CSRF

  • Basic concept: CSRF, also known as cross-site request forgery, English name cross-site request forgery
  • How to attack: Initiate malicious requests based on user login status.
  • How to Defend:
    • 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

What you need to know about Web security

Six, performance optimization

1. Network related

  • The DNS resolution beforehand
<link rel="dns-prefetch" href="//host_name_to_prefetch.com" />
Copy the code
  • Caching (see browser caching mechanism above)
  • Use HTTP / 2.0
  • Preloading – Can delay the loading of some important files that do not affect the first screen, which can reduce the first screen loading time, but the disadvantage is poor compatibility
<link rel="preload" href="http://example.com" />
Copy the code
  • Pre-render – Files to be downloaded are pre-rendered in the background
<link rel="prerender" href="http://example.com" />
Copy the code

2. Optimize the rendering process

  • Optimization at the code level (see how to reduce redraw and reflux in the Browser section)
  • Lazy execution – Putting some logic to use, which can be woken up by timers or events
  • Lazy loading – Delay loading of non-critical resources, such as images, videos, etc.

3. File optimization

Picture optimization:

  • If you can use CSS simulation instead, try not to use images
  • Small images are base64 format
  • Sprite figure
  • Choose the correct image format
    • Choose to use WebP format, small size, the disadvantage is poor compatibility
    • PNG is used for small images and SVG can be used for icon classes
    • Use JPEG for photos

Other file optimizations:

  • The CSS file is placedhead
  • The file compression function is enabled on the server
  • Place the script tag at the bottom of the body because JS file execution blocks rendering.
  • Script files are loaded asynchronously
    • Defer: Add the defer attribute to the script tag. Defer will be executed after the HTML has been parsed. If there are more than one, they will be executed in the order they were loaded
    • Async: Add async property to script tag. Async is executed immediately after loading. If there are more than one async, the execution order is independent of the loading order
  • For code that takes a lot of time to compute, consider using Webworker, which allows us to start a separate thread to execute the script without affecting rendering.
  • Use the CDN

4, other

Optimizing projects with Webpack:

  • For Webpackage 4, package projects using production mode, which automatically turns on code compression
  • Turn on Tree Shaking to remove useless code
  • Optimized images, for small images can be base64 written to the file
  • Split the code according to the route to achieve on-demand loading
  • Add hash to the packaged file name to achieve browser cache files

Error monitoring:

  • Running error
    • try… catch
    • window.onerror
  • Resource loading error
    • object.onerror
    • Advanced browserperformance.getEntries()You can obtain resources that have been loaded and monitor resources that have failed to be loaded
  • Cross-domain JS runtime error – add crossorigin attribute to script tag, then set access-Control-allow-origin to js resource response header
  • SourceMap files are generated when packaging for debug purposes

Error reporting:

  • Ajax communication is used to report
  • Make a request with the SRC of the IMG tag.

Seven, the framework

1. How to understand the MVVM pattern?

As the name implies, model-view-viewModel mode

  • Interface of the View:
  • Model: Data Model
  • ViewModel: Act as a bridge between View and Model

Advantages:

  • Decouple the View from the Model to reduce code coupling and increase the reuse of the View or logic
  • Automatically update the DOM, eliminating frequent DOM manipulation
  • Improve testability

Disadvantages:

  • It is difficult to debug bugs, such as writing some instructions in View, but it cannot be debugged by means of debugging
  • When a module is large, the Model is also large, which is prone to high memory overhead
  • For large graphics application sequences, ViewModel construction and maintenance costs will be high due to the large number of view states

2, Vue response type principle

Vue adopts the method of data hijacking combined with publishe-subscribe mode. Through Object.defineProperty(), it hijacks the setter and getter of each attribute to publish messages to subscribers when data changes and trigger corresponding listener callbacks.

  • The Observer traverses the data object, adding setters and getters to all properties, listening for changes to the data
  • Compile parses the template instructions, replaces variables in the template with data, initializes the render page view, and binds the corresponding node of each instruction to update function, adds subscribers to listen to the data, receives notification once the data changes, and updates the view
  • Watcher subscribers serve as a communication bridge between The Observer and Compile and do:
    • Add yourself to the attribute subscriber (DEP) during self instantiation
    • When notified of property changes to dep.notice(), its update() method is called and the callback bound in Compile is triggered

Interview question: Can you write a Vue two-way data binding? , I won’t post the code here.

3. Implementation principle of Virtual DOM

  • DOM is implemented through JS object emulation
  • The Dom tree diff algorithm, which compares the same layer (because in real business, Dom elements are rarely moved across layers), needs to judge three cases
    • No new nodes, nothing to do
    • The tagName and key of the new node are different from the old one, and the node is replaced directly
    • The new node’s tagName and key (which may not be) are the same as the old one, the attribute is determined and the subtree continues to be traversed
      • Determines whether the property has changed
        • Walk through the old property list to see if each property still exists in the new property list
        • Walk through the new property list to see if the existing property values have changed (and see if any new properties appear)
  • Rendering differences
    • The difference between two trees can be obtained by diff algorithm
    • Depth traverses the tree and updates the DOM according to the differences

There is also a list comparison algorithm for traversing child nodes, which deals with nodes with keys and existing lists. When the position of child nodes only changes, they will be replaced if compared according to the same layer, resulting in large DOM overhead. The list comparison algorithm will move nodes to update DOM by comparing the order of the old and new node lists, which can play a role of performance optimization in some cases.

For the Virtual Dom detailed code implementation can refer to: in-depth analysis: How to implement a Virtual Dom algorithm

4. Principle of front-end routing

Essence: Listens for URL changes and matches routing rules without refreshing the page.

Implementation method:

  • Hash based — better compatibility, but the ‘#’ is not aesthetically pleasing
    • Click jump or browser history jump: Trigger hashchange event -> Parse URL -> match to the corresponding routing rule
    • Manual refresh: Trigger the load event ->…
  • Based on the History API — HTML5 new routing scheme, more convenient and readable, poor compatibility
    • Browser actions such as forward or backward: Trigger popState event -> parse URL -> match to the corresponding routing rule
    • Click jump: Call pushState to add a state to the browser history ->…
    • Refresh the page or enter a URL: a request is made to the server, so using history requires a backend with redirection ->…

Interviewer: Do you know about front-end routing?

5. Comparison of advantages and disadvantages between Proxy and Object.defineProperty

Advantages of Proxy:

  • You can listen directly on objects instead of properties
  • You can listen for changes in the array directly
  • Multiple interception methods
  • The Proxy returns a new Object and can only manipulate the new Object for that purpose, whereas Object.defineProperty can only be modified directly by iterating through Object attributes
  • Proxy as the new standard will be the focus of browser vendors continued performance optimization

Object.defineproperty has the following advantages:

  • Good compatibility and support for Internet Explorer 9

6. Vue lifecycle

The process of creating initialization data, compiling templates, mounting DOM, rendering, updating, and unmounting.

  • BeforeCreate: at the beginning of the component instance creation and before the component properties take effect
  • Created: The component instance is fully created and properties are bound, but the real DOM has not been generated and $EL is not available
  • BeforeMount: Called before the mount begins, the associated render function is called for the first time
  • Mounted: El is invoked after the vm.$el is mounted to the instance
  • BeforeUpdate: Called before component data is updated and occurs before the virtual DOM is patched
  • Update: After component data is updated
  • Activited: Exclusive to keep-alive, invoked when the component is activated
  • Deadctivated: keep-alive only, called when the component is destroyed
  • BeforeDestory: Called before component destruction
  • Destoryed: invoked after component destruction

The difference between V-if and V-show

  • Dom destruction and reconstruction will occur when the V-if state is switched. Elements will not be rendered when the initial render condition is false.
  • V-show simply controls show and hide, and elements are always rendered regardless of initial conditions;
  • V-if is suitable for scenarios where conditions are rarely changed, and V-show is suitable for scenarios where conditions are frequently switched.

8. The difference between computed and Watch

  • Computed: A computing scenario commonly used to compare consumption performance. It is cached. Getters are cached after they are executed, and the next computed value is recalculated only after the value of the property it depends on changes
  • Watch: Often used to monitor and observe some dataprops,$emitOr a change in the value of this component to perform a callback for subsequent operations, no caching, the page is re-rendered when the value does not change will be executed.

9. What is the use of key in Vue

  • Keys with unique identifiers can improve the efficiency of diff algorithm, and list components in some complex scenes can be updated more accurately
  • In scenarios rendering simple stateless list components, performance is actually better without keys than with keys, because vUE will reuse nodes by default without keys, eliminating the overhead of destroying/creating components.

Reasons for using a unique identifier as a key are recommended:

  • Wearing a unique key can ensure that the state of the updated component is correct, avoiding bugs in some scenarios. Although it will increase the performance overhead, the user will basically feel no difference.

10, nextTick

NextTick allows us to perform deferred callbacks after the next DOM update cycle to retrieve the updated DOM.

  • Prior to Vue2.4, microTasks were used
  • The new version uses MicroTasks by default and MacroTasks in V-ON
  • The implementation of MacroTasks determines whether setImmediate can be used, then demots to MessageChannel, and then setTimeout

11. Method of communication between VUE components

  • props / $emit
  • $children / $parent— used by the parent componentthis.$childrenGets an array of child component instances that can be used in the child componentthis.$parentGets the parent component instance object.
    • Tips:#appGet on the$parentGet isnew Vue()Get an instance of the$parentIt isundefined; And the underlying subcomponent gets$childrenYou get an empty array.
  • provide / inject— Vue2.2 added API, the parent component throughprovideProperty to provide variables that can then be used in child componentsinjectTo inject variables.
  • ref / $refsrefWhen used on a normal DOM element, it refers to the DOM element. If on a child component, the reference is to a component instance
  • $attrs / $listeners— New to VUe2.4, cross-level component communication is possible
  • eventBus
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

// A.vue
<template>
  <div>
    <button @click="sendFirstName"></button>    
  </div>
</template>

<script>
import {EventBus} from './event-bus.js'
export default {
  data() {return{
      firstName:'leborn'
    }
  },

  methods:{
    sendFirstName(){
      EventBus.$emit('getFirstName', {firstName: this.firstname})}} </script> // vue <template> <div> {{name}}</div> </template> <script> import { EventBus } from'./event-bus.js'
export default {
  data() {
    return {
      name: ' '}},mounted() {
    EventBus.$on('getFirstName', param => {
      this.name = param.firstName + 'james';
    })
  }
}
</script>
Copy the code

12. Vue project performance optimization

Code level:

  • Suitable for V-if and V-show
  • Distinguish between computed and watch use
  • The V-for traversal adds the key to the item
  • V-for traversal avoids using v-if simultaneously
  • Events added via addEventListener are manually removeEventListener removed when the component is destroyed
  • Lazy loading of images
  • Route lazy loading
  • Third-party plug-ins are introduced on demand
  • SSR server rendering, fast loading of the first screen, good SEO effect

Webpack level optimization:

  • Compress the image
  • Extract common code using the CommonsChunkPlugin plugin
  • Extract the COMPONENT’s CSS
  • Optimize SourceMap
  • Build the result output analysis using the Webpack-Bundle-Analyzer visual analysis tool

Basic Web technology optimization:

  • Enable Gzip compression
  • Browser cache
  • The use of CDN
  • Use Chrome Performance to analyze Performance

For details, please refer to: Vue Project Performance Optimization — Practice Guide (most complete/detailed online)

React Lifecycle

Class ExampleComponent extends React.Component {// Used to initialize stateconstructor() {} / / used to replace ` componentWillReceiveProps `, this function will initialize and ` update ` when invoked / / because this function is static function, // If you want to compare 'prevProps', you need to maintain static getDerivedStateFromProps(nextProps, ShouldComponentUpdate (nextProps, nextState) {} shouldComponentUpdate(nextProps, nextState) {} shouldProps (props, nextState) {componentDidMount() {} // To get the latest DOM datagetSnapshotBeforeUpdate() {} // Components are about to be destroyed // You can remove subscriptions, timers, and so on herecomponentWillUnmount() {} // called after the component is destroyedcomponentDidUnMount() {} // called after component updatecomponentDidUpdate() {} // Render component functionsrender() {} // The following functions are not recommendedUNSAFE_componentWillMount() {}
  UNSAFE_componentWillUpdate(nextProps, nextState) {}
  UNSAFE_componentWillReceiveProps(nextProps) {}
}
Copy the code

14. When is setState synchronized and when is it asynchronous in React?

  • React raised event handlers (such as onClick). Calls to setState do not synchronize updates to this.state. The setState call to setTimeout/setInterval) executes this.state synchronously.

Reason: In setState, the isBatchingUpdates variable is used to determine whether this. State is synchronized. IsBatchingUpdates default to false meaning setState will synchronize this.state. However, when React calls the event handler, it will call the batchedUpdates function and change isBatchingUpdates to true. SetState will not synchronize this.state

  • What does the following code output
class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      val: 0
    };
  }
  
  componentDidMount() { this.setState({val: this.state.val + 1}); console.log(this.state.val); / / 1 timeslogthis.setState({val: this.state.val + 1}); console.log(this.state.val); / / 2 timeslog

    setTimeout(() => { this.setState({val: this.state.val + 1}); console.log(this.state.val); / / 3 timeslogthis.setState({val: this.state.val + 1}); console.log(this.state.val); / / 4 timeslog
    }, 0);
  }

  render() {
    returnnull; }};Copy the code
  • The first and second times are in the react lifecycle, isBatchingUpdates are true, and the state is not directly updated
  • Two sets of setState outside setTimeout are merged and executed only once, when state.val is 1
  • SetTimeout triggers isBatchingUpdates to be false, and setState is executed with output 2, 3

Output: 0, 0, 2, 3

At the end

The front-end knowledge point is too much and too miscellaneous, for some not involved content, such as Webpack, Babel and so on May be supplemented later. If this article can help you, please like it. Please forgive me for not helping you

Finally, I suggest that you can summarize some technical articles by yourself, otherwise it is easy to forget, yes the blogger is so, and then the article if there is no rigorous place, you are welcome to point out the comment area.

reference

  • The way to advance the front end
  • Wood and poplar front end advanced