CSS

The box model

Box-sizing :'content-box'// Box-sizing :'border-box'// box-sizing:'border-box'//Copy the code
  • Standard box model

The width of the element is equal to the width of width+margin+border+padding in style

  • Weird box model

This includes border and padding, and the width of the element is equal to the width of the style element

Em and REM

  • em

Font-size :12px; span :2em; 21*2=24px

  • rem

HTML is set to font-size:12px, and when div is 2rem, it is 24px

Display: None and visibility:hidden

  • Display: None Hides the corresponding element, no more space is allocated to it in the layout of the document, and its edges are closed as if it never existed.

  • Visibility: Hidden the corresponding elements, but retain the original space in the document layout.

Explain float and how it works?

Floating elements leave the document flow and do not take up space. The floating element touches the border that contains it or stays in the border of the floating element.

  • Clear float with empty tags: This method adds an empty tag definition to all float tagscss clear:bothThe downside is thatAdded meaningless tags.
  • Use Overflow: Set overflow to hidden or auto, and add CSS attributes to parent tags that contain floating elementsoverflow:auto; zoom:1; zoom:1Compatible with Internet Explorer 6.
  • useafterPseudo-object cleanup float: This method only applies to non-Internet Explorer browsers. In this method, you must set height:0 for the pseudo-object that you want to clear the floating element, otherwise the element will be several pixels higher than it really is.
box:after{ 
content:"."; 
height:0; 
visibility:hidden; 
display:block; 
clear:both; } 
Copy the code

Problems caused by floating elements

The height of the parent element cannot be split. Elements affecting the parent element and non-floating elements (inline elements) at the same level as the floating element will follow. If not the first element floats, the elements preceding that element will float as well, otherwise the structure of the page will be affected

Horizontal vertical middle implementation method

  • flex
.box{
	display:flex
	justify-content:center;
	algin-items:center;
	.inner{
		
	}
}
Copy the code
  • Position needs to know the width and height
.box{
positon:relative
width:300px
height:300px
	.inner{
	position:absoult
	top:50%,
	left:50%,
	margin-left:-100px;
	margin-top:-100px;
	width:200px;
	height:200px
	}
}
Copy the code
  • Position does not need to know the width and height
.box{ positon:relative .inner{ position:absoult top:0, left:0, bottom:0; right:0; margin:auto; }}Copy the code
  • With the deformation
.box{
positon:relative
	.inner{
	position:absoult;
	top:50%;
	left:50%;
	transform:(-50%,-50%)
	}
}
Copy the code
  • table-cell
display:table-cell vertical-algin:middle; .inner{ width:100px; height:100px; margin:0 auto; }}Copy the code

BFC

  • What is landing

A block formatting context is a separate rendering area that keeps elements in the BFC isolated from other elements.

  • How to generate BFC
Display: flex/inline - block; float; position; overflow:hiddenCopy the code
  • The characteristics of landing
  • Is a separate container, the inside is not affected by the outside
  • The boxes are arranged vertically, one at a time, from the topmargindecision
  • Margins overlap between two block-level boxes in the same BFC

The height of the margin is equal to the greater of the folded margins = “margin:10px 0 should be 20px apart in the middle, but they overlap, only 10px apart

  • Solve margin overlap: Create a different BFC to avoid margin folding
  • What does the BFC do?

The biggest effect is to have a separate container on the page so that elements inside the container do not interact with those outside the container

Flex layout

Ruan yifeng’s tutorial is very detailed, so I won’t go into the Flex layout tutorial: Syntax – Ruan Yifeng’s weblog

JAVASCRIPT

JS basic data type

Number, a string,null,undefined,BooleanAnd symbolCopy the code

JS array operations

  • mapIterate through the array, returning a new array of values returned by the callback function
  • filterFilter, returns true to keep the element in the new array, false to delete it
Array.prototype.filter=function(fn){
	let newArr=[]
	//this is the original array; Loop through the array, performing a callback and returning if true
	for(let i=0; i<this.length; i++){let flag=fn(this[i])
	flag&&newArr.push(this[i])
	}
	return newArr
}
Copy the code
  • forEach, can’tbreak, you can usetry/catchIn thethrow new ErrorTo stop
  • everyIf one item returns false, the whole item returns false
Array.prototype.every=function(fn){
	let newArr=[]
	for(let i=0; i<this.length; i++){let flag=fn(this[i])
	if(! flag){return false}}return flag
}
Copy the code
  • someIf one item returns true, the whole item returns true
Array.prototype.some=function(fn){
	let newArr=[]
	for(let i=0; i<this.length; i++){let flag=fn(this[i])
	if(flag){
	return flag
	}
   }
	return false
}
Copy the code
  • join, the specific symbol is converted to a string
  • pushPush an element to the last digit of the array
  • reduce
Reduce (function(total, currentValue, currentIndex, ARR), initialValue) // Current index, 'arr' : original array, 'initialValue' : initialValue passed to the functionCopy the code
  • unshift/shift: Adds/removes elements at the beginning of the array, changing the array
  • splice(start, number, value): Returns an array of deleted elements, changing the original array

closure

  • What is a closure

Function A contains function B, and function B refers to A variable of function A. A closure is A function that reads variables inside other functions

  • Characteristics of closures
  1. Function nested inside function
  2. Internal functions can refer to arguments and variables of external functions
  3. Parameters and variables are not collected by the garbage collection mechanism
  • Understanding closures

Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have the concept of scope

Understanding of this

  • This always refers to the caller of the function
  • If there’s new, this is referring to the object that came out of new
  • Event, this is the object that triggers the event

What does the new operator do

  1. First the function takes unquantified arguments. The first argument is the constructor, and the following arguments are used by the constructor
  2. Then internally create an empty object obj
  3. Because the OBj object needs to access properties on the constructor prototype chain, it can passobj.__proto__=constr.prototype
  4. Bind obj to the constructor and pass in the rest of the arguments
  5. Finally, check whether the constructor returns the value as an object. If the object uses the value returned by the constructor, if not, use obj
function creatNew(constr,... args){
	let obj={}
	obj.__proto__=constr.prototype
	let res=constr.apply(obj,args)// The constructor's this refers to the obj and passes the argument
	return res instanceof Object ? res : obj
}
Copy the code

Reflow and Repaint

  • Redraw: Once the elements are styled, the browser will draw them for their properties
  • Backflow: The browser rerenders the page when the size, position, structure, or attributes of the element are triggered. This is called backflow. Because the browser needs to recalculate, after the calculation and layout, is a heavy operation, so the loss is high. There must be a redraw

What can trigger backflow

  • Font size changes
  • Page first render
  • Element position, size, and content change
  • Add or remove visible DOM elements
  • Activate pseudo-classes such as Hover

Debounce and Throttle

  • Image stabilization

User input verification: triggers a high-frequency event and executes the function only once within n seconds

function debounce(fn){
	let timer=null
	clearTimeout(timer)
	timer=setTimeout(() = >{
		fn.apply(this.arguments)
	},500)}Copy the code
  • The throttle

Page scrolling, or resize, is performed at regular intervals

function throttle(fn){
	let canRun=true // Save a tag first
	if(! canRun)return
	canRun=false // Set canRun to false to prevent it from being executed before it is executed
	setTimeout(() = >{
		fn.apply(this.arguments)
		canRun=true // After executing the event (such as calling the interface), reset the flag to true
	},500)}Copy the code

The difference between the two is as follows: Intercept is performed once in a specified period of time. For example, if the user enters wait for 5 seconds, the intercept is performed five times, and the anti-shake is performed only once

Prototype chain

Property lookup: Work your way up from the instance itself until you access the prototype of the object. Attribute modification: only the attribute of the instance object itself will be modified. If it does not exist, the attribute will be added. If you need to modify the attribute of the prototype, you can use f.prototype. XXX = XXX. This, however, changes the properties of all instances that inherit from the constructor F.

scope

Scope of variables and declarations. It can be divided into block-level scope and function scope

Here’s a classic interview question to help you understand

var name1 = "haha";
    function changeName(){
        var name2="xixi";
        function swapName(){
            console.log(name1);//haha
            console.log(name2);//xixi
            console.log(tempName)//undefined
            var tempName=name2;
            name2=name1;
            name1=tempName;
            console.log(name1);//xixi
            console.log(name2);//haha
            console.log(tempName);//xixi
        }
        swapName();
        console.log(name1);//xixi
        console.log(name2);//haha
       // console.log(tempName); Uncaught ReferenceError: tempName is not defined
    }
    changeName();
    console.log(name1);//xixi
   // console.log(name2); Uncaught ReferenceError: name2 is not defined
   // console.log(tempName); Uncaught ReferenceError: tempName is not defined
Copy the code

Copy of object (shallow and deep copy)

  • Shallow copy

Copy a reference object as an assignment, pointing to the same address and affecting the original object when it is modified (addressing operations, e.g., accessing data of type array).

Object.assign()
Array.slice() expansion operator (...)Copy the code
  • Deep copy

Copy a new object completely without affecting the original object (search operation, for example: access data type string)

JSON.parse(JSON.stringify(obj)): // The fastest performance
Copy the code

Disadvantages:

  • Parse json. stringify if there is a time object in obj, the time will be a string, not an object, as a result of json. stringify.
  • If obj contains RegExp(short for regular expression), Error objects, then serialization results in empty objects.
  • If obj has a function called undefined, the serialization result will lose the function or undefined.
  • If obj has NaN, Infinity, and -infinity, the serialized result becomes null;
  • Json.stringify () serializes only the enumerable properties of the object itself, for example: if the object in obj is generated by a constructor, the constructor of the object is discarded after using json.parse (json.stringify (obj)) deep copy;

Handwritten deep copy (recursive assignment)

function deepClone(val){
	let objClone=Array.isArray(val)? [] : {}if (val && typeof val==='object') {for(key in val){
			if(val.hasOwnProperty(key)){
				// Determine whether the obj child is an object, if so, recursively copy
		        if(val[key] && typeof val[key] === "object") {
		          objClone[key] = deepClone(val[key]);
		        } else {
		          // If not, simply copyobjClone[key] = val[key]; }}}}return objClone
}
Copy the code

The function is currified

  • What is a function Coriolization?

By converting a multi-parameter function into a series of nested functions, each of which takes one argument in turn, this is called function corrification.

function curry(fn, len = fn.length) {
  return _curry.call(this, fn, len)
}

function _curry(fn, len, ... args) {
  return function (. params) {
    console.log(params);
    let _args = [...args, ...params];
    console.log(_args);
    if (_args.length >= len) {
      return fn.apply(this, _args);
    } else {
      return _curry.call(this, fn, len, ... _args) } } }let _fn = curry(function (a, b, c, d, e) {
  console.log(a + b + c + d + e)
});

_fn(1.2.3.4.5); / / 15
_fn(1) (2) (3.4.5); / / 15
_fn(1.2) (3.4) (5); / / 15
_fn(1) (2) (3) (4) (5); / / 15
Copy the code

inheritance

// Use prototype inheritance
function Father(){
this.name='father'
}
function Child(){
this.age=10
}
child.prototype=new Father();// Inherit on the prototype
var demo=new Child()
consloe.log(demo.name) // father


// change this with call and apply
function Father(){
this.name='father'
}
function Child(){
Father.call(this)
this.age=10
}
Copy the code

Promise

Handwritten Promise suggest see the promise source implementation (perfect compliance with the Promise/A+ specification), according to the specification more detailed!

Here are some interview questions I collected to make them easier to understand

const first = () = > (new Promise((resolve,reject) = >{
    console.log(3);
    let p = new Promise((resolve, reject) = >{
         console.log(7);
        setTimeout(() = >{
           console.log(5);
           resolve(6); 
        },0)
        resolve(1);
    }); 
    resolve(2);
    p.then((arg) = >{
        console.log(arg);
    });

}));

first().then((arg) = >{
    console.log(arg);
});
console.log(4);
Copy the code

The first event loop

First execute the macro task, the main script, new Promise immediately execute, print [3], execute the new Promise operation p, print [7], find setTimeout, put the callback into the Event Queue of the next task, then of P, let’s call then1, Put it in the microtask queue, find the then of first, called then2, put it in the microtask queue. Execute console.log(4), output [4], and the macro task is finished. Then execute the micro task, execute then1, output [1], execute then2, output [2]. This is the end of the first event loop. Start the second round.

Second cycle of events

First execute the callback of setTimeout in the macro task, and output [5]. The resovle doesn’t work because once the state of p changes, it doesn’t change. So the final output order is 3, 7, 4, 1, 2, 5.


async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    console.log('async2');
}
console.log('script start');
setTimeout(function() {
    console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
    console.log('promise1');
    resolve();
}).then(function() {
    console.log('promise2');
});
console.log('script end');
Copy the code
  1. The output script start

Console. log(‘ script start ‘); console.log(‘ script start ‘);

  1. Output saync1 start

When async1 is executed, the function defined by an async expression is executed immediately

  1. Output saync2

Since async2 is a function defined by async, it prints async2 and returns a Promise object

  1. Output promise1

Because it’s implemented to new Promise, which is implemented immediately, print promise1

  1. The output script end

The previous step prints promise1, then executes resolve, then jumps out of the promise and continues, printing script end

  1. Output promise2

Because the previous New Promise was put into the resolve callback, resolve is put on the call stack to execute

  1. Output async1 end

Since the promise defined by await has finished and returned the result, continue the task after async1, which is console.log(‘ async1 end ‘).

  1. Output setTimeout

const promise = new Promise((resolve, reject) = > {
    resolve('success1');
    reject('error');
    resolve('success2');
});

promise.then((res) = > {
    console.log('then:', res);
}).catch((err) = > {
    console.log('catch:', err);
})
Copy the code

Once the promise state changes, it doesn’t change again, so reject(‘error’) doesn’t work. It just says then then: Success1

The event queue

Understand Event Loop once and for all

Node11 eventloop execution is now consistent with the browser after version 11, node11 is now in the timer phase setTimeout,setInterval... And immediate in the check phase are both modified on Node11 to execute the microtask queue as soon as a task in a phase is executed.

  • Eventloop for the browser

Browser (multi-process) includes the Browser process (the main process of the Browser), third-party plug-in process and GPU process (Browser rendering process). The GPU process (multi-thread) is closely related to the Web front end and contains the following threads:

  • GUI rendering thread
  • JS engine thread
  • Event-firing thread (closely related to EventLoop)
  • Timing trigger thread
  • Asynchronous HTTP request threads

There are two types of tasks in JS: macro tasks and micro tasks

  • Macro tasks: script (main code block),SetTimeout, setInterval, setImmediate, I/O
  • Microtasks: process.nexttick (nodejs),Promise, Object.observe, MutationObserver

The difference between the two:

  • Macro tasks are code that executes on each execution stack (including fetching event callbacks from the event queue and placing them on the execution stack at a time)
  • In order to enable an orderly switch between the JS engine thread and the GUI rendering thread, the browser will re-render the page after the current macro task ends and before the next macro task starts (macro task > Render > Macro task >…).
  • Micro tasksIn the currentMacro taskTasks performed immediately after execution (tasks performed after the current macro task and before UI rendering). Microtask response speed compared tosetTimeout(The next macro task) will be faster because you don’t have to wait for UI rendering.
  • After the current macro task executes, all microtasks generated during its execution are executed.

How is the task queue managed by event-triggering threads generated?

When the main thread is running, it will generate an execution stack. When the code in the stack calls some asynchronous APIS, it will add events to the task queue. After the execution of the code in the stack, it will read the events in the task queue and execute the corresponding callback function of the event.

The specific flow of executing a JavaScript code:

  1. Execute global Script synchronization code, some of which are synchronous statements, some of which are asynchronous statements (setTimeout, etc.);
  2. After executing the global Script code, the call Stack is emptied;
  3. Remove the callback task at the beginning of the microtask queue from the microtask queue and put it into the call Stack for execution. After execution, the length of the MicroTask queue decreases by 1.
  4. Continue fetching the task at the top of the queue, place it on the call Stack, and so on until all the tasks in the MicroTask Queue have been executed. Note that if a microtask is created in the process of executing it, it is added to the end of the queue and executed during this cycle.
  5. When all tasks in the MicroTask Queue are completed, the MicroTask Queue is empty and the call Stack is empty.
  6. Remove the task at the head of the macroTask queue and add it to the Stack for execution.
  7. After the execution, the call Stack is empty.
  8. Repeat steps 3-7;
  9. Repeat steps 3-7;
  10. .
  • Event queues in Node.js
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ > │ timers │ < -- -- --, perform setTimeout (), setInterval () callback │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ | | < -- perform all Next Tick Queue and MicroTask Queue callback │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ │ pending callbacks │ < -- --, performed by a Tick on the delay of the I/O Callback (to be perfected, Negligible) │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ | | < -- perform all Next Tick Queue and MicroTask Queue callback │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ │ idle, Prepare │ < - - - - - internal call (negligible) │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ | | < -- perform all Next Tick Queue and MicroTask Queue callback | | ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ incoming: │ ├ ─ execute almost all callbacks, In addition to the close callbacks, timers, setImmediate) │ │ poll │ < ─ ─ ─ ─ ─ ┤ connections, │ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ │ data, Etc. │ │ | | | | | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ | | < -- perform all Next Tick Queue and MicroTask Queue callback | ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ │ Check │ < -- -- setImmediate () callback will be at this stage to perform │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ | | < -- perform all Next Tick Queue and MicroTask Queue callback │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ └ ─ ─ ┤ close callbacks │ < -- -- socket. On (' close ',...). └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘Copy the code

Share your understanding of AMD and Commonjs

CommonJS is the specification for server-side modules, which Is adopted by Node.js. The CommonJS specification loads modules synchronously, meaning that subsequent operations cannot be performed until the load is complete. The AMD specification loads modules asynchronously and allows you to specify callback functions. The AMD recommended style exposes module objects by returning an object as a module object. The CommonJS style exposes module objects by assigning values to module.exports or exports properties.

Vue

The responsive principle of Vue

Implementation principle of MVVM (write a simple Vue by hand)

The responsivity of Vue is the hijacking of data via Object.defineProperty, implemented in conjunction with the observer pattern. Vue uses object.defineProperty to create an observe to hijack all properties and convert them to getters and setters. For each component instance in Vue, there is a Watcher instance that collects dependencies through getters for used data properties during component rendering. Watcher is then notified when the setter for the dependency fires, causing its associated component to be re-rendered.

  • Observer: The ability to listen for all attributes of a data object and notify subscribers of any changes to the latest values.

The core of the Observer is to listen for changes in data through Object.defineProprty(). This function defines the setter and getter internally and fires the setter whenever the data changes. At this point, the Observer informs the subscriber, who is Watcher

  • Compile: Scans and parses the instructions of each element node, replaces the data according to the instruction template, and binds the corresponding update function.

Compile mainly does is parses the template instructions, replaces the variables in the template with data, initializes the render page view, binds the corresponding node of each instruction to update function, adds the subscriber that identifies the data, receives notification when the data changes, and updates the view

  • Watcher: bridge between Observer and Compile, subscribe to and receive notification of each property change, execute the corresponding callback function bound by the directive, and update the view.

Watcher subscribers, acting as a bridge between the Observer and Compile, mainly do the following:

  • To the attribute subscriber on its own instantiation(dep)Add yourself inside
  • You have to have one of themupdate()methods
  • Pending attribute changedep.notice()Can call its ownupdate()Method and triggerCompileThe callback bound to

Advantages and disadvantages of proxy and Object.defineProperty

  1. Proxy can listen directly for objects rather than attributes and return a new Object, whereas Object.defineProperty can only be modified directly by iterating through Object attributes
  2. You can listen for changes in the array directly
  3. Interception methods are many, not limitedApply, ownKeys, deleteProperty, hasAnd so on Object. DefineProperty does not have
  4. Proxy is a new feature in ES6 and is not compatible. Object. DefineProperty is compatible with IE9

Why 2.0 doesn’t use proxy: Although the new attribute of ES6 appeared as proxy at that time, it was not compatible with polyfill and could not be compatible. However, in the version of VUe3.0, it would effectively provide a compatible solution. In 3.0, proxy does not set get and set methods for attributes like Object.defineProperty. So the proxy does not trigger a circular call.

The difference between computed and Watch

  1. Computed is a calculated attribute, used mostly in scenarios where values are computed, and watch is listening for a worthwhile change
  2. Computed is cached. Computed values are cached after the getter is executed. Only after the property values on which it depends are changed, the corresponding getter is called again the next time the computed value is obtained. Watch executes a callback every time the listening value changes
  3. For computed functions, return is mandatory; watch is not

General process for computed caching:

In the presence of watcher, the watcher. Dirty attribute is used to determine whether this computed attribute needs to be reevaluated, because during the last round of dependency collection, the watcher was added to the dependency array by observation and observation. If the observer changes, Dep.notify () is used to notify all watchers, and for computed and watcher changes, watcher.dirty=true indicates that the observer has changed. The computed property is recalculated when the getter is called again, otherwise the previously cached value is used.

Component communication

  • Props (Father to son)
  • $emit(Child to Father)
  • $attrswith$listeners
  • Dojo.provide and inject
  • bus.js

Specifically refer to the vUE 8 component communication methods, worth collecting!

nextTick

A deferred callback is performed after the next DOM update loop ends. Immediately after the data is modified, the callback function is used to get the updated DOM

For specific principles, please refer to the principles and uses of Vue.nextTick

keep-alive


is an abstract component that keeps an instance of an inactive component in memory rather than destroying it directly. It is an abstract component that is not rendered into the real DOM and does not appear in the parent component chain.

  • Set the cache for the first rendering
  • Provides two life hooks, Actived and deactived. Because keep-alive saves the component to memory and does not destroy or rebuild it, methods such as creted are not called. Instead, two hooks, actived and deactived, are used to determine whether the component is active.
  • The keep-alive component provides include and exclude attributes for conditional caching, both of which can be represented as comma-separated strings, regular expressions, or arrays.

Principle This section describes the implementation principle of keep-alive and LRU cache policy

Why is the data of a component written in functional form

Vue components are reusable. After a component is created, it can be reused in multiple places. However, no matter how many times it is reused, the data in the component should be isolated from each other and not affected by each other. Changes to the data of each reusable component should not affect the data of other reusable components. To achieve this effect, data cannot be a pure object, but is in the form of a function return value, so each component instance can maintain a separate copy of the data without affecting each other.

Vue template compilation principles

An ABSTRACT syntax tree (AST), where the AST is no longer afraid of being asked Babel, Vue compilation, Prettier, etc

HTTP

Main features of THE HTTP protocol

  1. Simple and fast [URIs are fixed and easy to operate]
  2. Flexible [HTTP protocol has a header, one HTTP protocol can complete the transfer of different data types]
  3. Stateless [unable to distinguish between two connection states because it will break]
  4. No connection [Once connected, it will break]

Get and POST

  1. Get fallbacks are harmless; POST resubmits the request
  2. Get is not secure and the information is exposed in the URL
  3. The GET argument is passed through the URL, and the POST is placed in the Requset Body
  4. GET request parameters are fully preserved in browser history, while POST parameters are not

Component of an HTTP packet

  • The request message
  1. The request line
  2. Request header
  3. A blank line
  4. Request body
  • The response message
  1. The status line
  2. Response headers
  3. A blank line
  4. Response body

The HTTP request has four parts

  • HTTP request methods or actions, such as get or POST requests;

  • The URL being requested (requested address);

  • Request header, which contains some client environment information, authentication information, etc.

  • The request body (request body) can contain the query string information and form information submitted by the customer.

    Fields in the request header

  • Accept:text/ HTML,image/*
  • Accept-charaset :ISO-8859-1 [Accept character code :ISO-8859-1]
  • Accept-encoding :gzip/compress
  • Accept-language :zh-cn[browser supported Language]
  • Host:localhost:8080
  • If-modified-since :Tue, 09 May 2017 01:34:02 GMT
  • The user-agent: Nozilla / 4.0 (Com)… [Tell the server my browser kernel, client environment letter]
  • Cookie: [authentication information]
  • Connection:close/ keep-alive [Keep link Alive, I don’t close link after sending data]

The HTTP response has three parts

  • A numeric and literal status code that indicates whether the request was successful or failed;

  • The response header, like the request header, contains a lot of useful information, such as the server type, date and time, content type, and length;

  • Response body (response body).

    Fields in the response header

  • Cache-control :[tells the browser how to Cache the page (because browser compatibility is best with two)]
  • Connection:close/ keep-alive [Keep link Alive, I don’t close link after sending data]
  • Content-Type:text/html; Charset = GB2312 [Content format and encoding]
  • Last-modified :Tue,11 Juj,2017 18 18:29:20[Tell the browser when the resource was Last updated]
  • ETag: “540-54 f0d59b8b680”
  • Expires:Fri, 26 May 2017 13:28:33 GMT [Expires date]
  • Server: Apache Tomcat nginx

What is a persistent connection

HTTP adopts the “request-reply” mode. In the common mode (except keep-alive mode), each request/reply client and server create a connection and disconnect the connection immediately (HTTP is a connectionless protocol).

When the keep-alive mode is used, the keep-alive function keeps the connection from the client to the server Alive and prevents the establishment or re-establishment of the connection when subsequent requests to the server occur

HTTP keep-alive and TCP keep-alive

  • http

Keep-alive is designed to keep TCP alive longer so that multiple HTTP packets can be sent over the same connection, increasing socket efficiency.

  • tcp

Keep-alive is used to check the status of TCP connections. Note: Keep-alive is only available in version 1.1

TCP’s three handshakes and four waves

Interview: Tell me what happens between the time you enter the URL and the time the page loads

HTTP and HTTPS

HTTP is usually carried over TCP. A security layer (SSL or TSL) is added between HTTP and TCP. The default HTTP port number is 80, and HTTPS port number is 443

HTTPS has a lower performance than HTTP because SSL/TLS has several handshakes and encryption and decryption processing, but encryption and decryption processing can already be accelerated by special hardware.

Tell me what the seven layers of the network model are

  1. The application layer
  2. The presentation layer
  3. Session layer (from top to bottom) (HTTP, FTP, SMTP, DNS)
  4. Transport layer (TCP and UDP)
  5. Network Layer (IP)
  6. The physical layer
  7. Data Link Layer (Ethernet)

Cross-domain solutions

  1. jsonp
  • The principle of the json

Web pages can get JSON data dynamically generated from other sources by taking advantage of the

  • Jsonp implementation process
  1. Declare a callback function whose name is passed as a parameter value to the server requesting data across domains, and whose parameter is to fetch the target data (the data returned by the server).
  2. To create a<script>Tag, assign that cross-domain API data interface address to<script>SRC, and pass the function name to the server at this address.? callback=show)
  3. When the server receives the request, it needs to do something special: concatenate the function name passed in with the data it needs to give you into a string. For example, the function name passed in is show, and the data it prepares is show(‘resData’).
  4. Finally, the server returns the data to the client through HTTP protocol, and the client invokes and executes the previously declared callback functionshowTo operate on the returned data
  1. CORS

To enable CORS, set access-Control-allow-Origin on the server. This attribute indicates which domain names can access resources. If a wildcard is set, all websites can access resources.

  1. Nginx reverse proxy

Nginx configure a proxy server (domain name and domain1 the same, different port) as a jumper, reverse proxy access to domain2 interface, and can incidentally modify the cookie in the domain information, convenient for the current domain cookie writing, cross-domain login.

Common HTTP status codes

  • 1XX (provisional response) :

A status code that represents a temporary response and requires the requester to continue with the operation.

  • 2XX (Success) :

A status code indicating that the request was successfully processed. 200 (success) : The server successfully processed the request. Typically, this means that the server has provided the requested web page.

  • 3XX (Redirection) : Further action is required to complete the request.
  1. 301 (Permanent move) : The requested page has been permanently moved to a new location.
  2. 302 (Temporary movement) : The server is currently responding to requests from web pages in different locations, but the requester should continue to use the original location to respond to future requests.
  3. 304 (unmodified) : The requested page has not been modified since the last request.
  • 4XX (Request error) : These status codes indicate that the request may be in error, preventing the server from processing it.
  1. 400 (error request) : The server does not understand the syntax of the request.
  2. 404 (not found) : The server could not find the requested page.
  • 5xx (server error) :

These status codes indicate that an internal error occurred while the server was processing the request.

  1. 500 (server internal error) : The server encountered an error and could not complete the request.
  2. 503 (Service unavailable) : The server is currently unavailable (due to overloading or downtime for maintenance).

Principle of CDN

Content Delivery Network (CDN) is a Content Delivery Network. CND has established computer rooms and deployed a large number of nodes in major cities around the world. When a user accesses a network, the Global Sever Load Balance (GSLB) algorithm is used to locate the nearest node. Commonly known as the principle of proximity.

HTTP caching mechanism

HTTP caching is a browser file level caching mechanism based on HTTP protocol. In the case of repeated requests for files, the browser can determine expires based on the protocol header whether to request the file from the server or to read the file locally. If the file does not expire, the browser directly reads the HTTP cache file

  • Strong cache

Hit the cache

The difference between Expires and Cache-Control

- Expires is used to Control the expiration date of the Cache. - cache-control Is used to Control the Cache of the web page. Common values include 'private, no-cache, max-age, and must-revalidate. `Copy the code
  • Negotiate the cache

Negotiate with the server whether caching is allowed

What is the Etag

Last-modified is used with the HTTP header of the ETag request to take advantage of the cache of the client, such as the browser. ETag is used to identify the status of a resource. When a resource changes, if one or more of its headers or message entities change, the ETag changes. As the browser downloads components, it stores them in the browser cache. If it needs to fetch the same component again, the browser will check the cache time of the component. If it has expired, the browser will send a conditional GET request to the server. The server determines that the cache is still valid and sends a 304 response telling the browser that it can reuse the cached component.

What do you know about Http 2.0?

HTTP/2 introduces the concept of “server push,” which improves performance by allowing the server to proactively send data to the client cache before the client needs it. HTTP/2 provides more encryption Support HTTP/2 uses multiplexing, which allows multiple messages to cross simultaneously over a connection. It increases header compression, so that even for very small requests, the headers for both the request and the response take up only a small percentage of bandwidth.

Common Web security and defense principles

  • SQL injection

The principle is to trick the server into executing malicious SQL commands by inserting SQL commands into Web forms to submit or enter query strings for domain names or page requests.

  • XSS refers to an attacker inserting malicious intent into a Web pageHTML tagsorJavascript code.

For example, an attacker puts a seemingly secure link in the forum, tricking users into clicking on it and stealing the user’s private information in the cookie; Or an attacker could add a malicious form to a forum, and when a user submits the form, it sends the information to the attacker’s server instead of the trusted site the user thought it was.

  • CSRF

CSRF is to complete the specified action on behalf of the user, and need to know the code and packets of other users’ pages. To complete a CSRF attack, the victim must complete two steps in sequence:

  1. Log in to trusted website A and generate cookies locally.
  2. Visit dangerous site B without logging out of A.

webpack

How to optimize the first screen loading

  1. Vue-router Indicates lazy route loading

  2. Entry file: Manually configure webpack multiple entries

In this way, two unrelated JS modules can be loaded in parallel, which is faster than loading a JS module of the same size. But there are problems:

  1. If both JS files incorporate LoDash, then LoDash will be packaged into both JS modules at the same time
  2. Inflexible, unable to dynamically split code according to the logic of the core application
var path = require('path');
var root_path = path.resolve(__dirname);
module.exports = {
    mode: 'production'.entry: {  // configure multiple entry files packaged into multiple code blocks
        index: path.resolve(root_path, 'index.js'), 
        a: path.resolve(root_path, 'a.js')},output: {
        filename: '[name].bundle.js'.path: path.resolve(root_path, 'dist')},module: {
        rules: [{test: /\.js$/,
                loader: 'babel-loader'.exclude: path.resolve(root_path, 'node_modules'),
                include: root_path
            }
        ]
    }
}
Copy the code
  1. Avoid repetition: usesplitChunksThe plug-in removes and extracts the common code block as a separate onechunk

Webpack.config.js uses SplitChunks:

optimization: {
     splitChunks: {
         chunks: 'all'}}Copy the code

Lodash is separately packaged as Venders ~a~index.bundle.js, SplitChunks can also be configured according to their own requirements, the default configuration is as follows:

  1. Modules are referenced repeatedly or come from modules in node_modules
  2. Minimum 30KB before compression
  3. When loading on demand, the number of requests is less than or equal to 5
  4. At initial load, the number of requests is less than or equal to 3

Modules that meet the above criteria are split into a single code block

  1. CDN acceleration is used to extract the common library from vendor

  2. Webpack turns on gzip compression

Use the plug-in CompressionWebpackPlugin

const CompressionWebpackPlugin = require('compression-webpack-plugin')module.exports = {" plugins ": [new CompressionWebpackPlugin] 
}
Copy the code
  1. Vue asynchronous components
  2. Server rendering SSR
  3. Load the UI component library on demand
  4. Rel attribute Settings using the Link tag:
  • prefetch(This resource will be used in some future navigation or function, but the download order weight of the resource is low. Prefetch is usually used to speed up the next navigation.)
  • preload(Preload will increase the weight of the download order of resources, so that key data can be downloaded in advance, optimize the page opening speed)

What are the common loaders

  • file-loaderExport files to a folder, referencing the output file in code with a relative URL (handling images and fonts)
  • url-loader: Similar to file-loader, the difference is that you can set a threshold. If the threshold is greater than the threshold, publicPath is returned. If the threshold is smaller than the threshold, base64 encoding (processing images and fonts) is returned.
  • image-loader: Loads and compresses image files
  • babel-loader: Converts ES6 to ES6
  • sass-loader: The CSS code is injected into JavaScript, and the CSS is loaded through DOM manipulation
  • css-loader: Loads the CSS, supporting features such as modularization, compression, and file import
  • vue-loader: Loads the vue.js single file component

What are the common plugins

  • html-webpack-pluginYou can automatically generate HTML code from templates and reference CSS and JS files
  • extract-text-webpack-plugin Separate styles referenced in the JS file into a CSS file
  • DefinePluginConfigure global variables at compile time
  • HotModuleReplacementPluginHot update
  • happypackAccelerate code building through a multi-process model

The difference between loader and plugin

  • Loader is essentially a function that converts received content and returns the converted result. (equivalent to a translation officer), pre-processing the translation of other types of resources

  • Plguin is a plug-in that extends the functionality of WebPack

Principle of thermal renewal

Hot updates to Webpack are also known as Hot Module Replacement, or HMR. This mechanism allows you to replace the old module with the new one without refreshing the browser.

The figure above is a module hot update flow chart of Webpack with Webpack-dev-server for application development.

  1. In WebPack’s Watch mode, when a file in the file system changes, WebPack listens for the file change, recompiles and packages the module according to the configuration file, and saves the packaged code in memory through simple JavaScript objects.

  2. The second step is the interface interaction between Webpack-dev-server and Webpack. In this step, it’s mainly the interaction between Webpack-Dev-middleware of Dev-server and Webpack. Webpack-dev-middleware calls the API exposed by Webpack to monitor code changes and tells Webpack to pack the code into memory.

  3. The third step is a monitoring of file changes by Webpack-dev-server, which is different from the first step in that it does not monitor code changes for repackaging. . When we are in the configuration file is configured with devServer watchContentBase to true, the Server will listen to these configuration static files in the folder change, change will notify the browser after the live for the application to reload. Notice that this is browser refresh, and HMR are two different things.

  4. The fourth step is also the work of the webpack-dev-server code. This step mainly uses sockJS (webpack-dev-server dependency) to establish a websocket long connection between the browser and the server. This tells the browser about the status of the various stages of the Webpack compilation and packaging, as well as the information that the Server listens for static file changes in step 3. The browser performs different operations based on these socket messages. Of course, the most important information passed by the server is the hash value of the new module, and the subsequent steps use this hash value to perform module hot replacement.

  5. The webpack-dev-server/client cannot request updated code and does not perform hot module operations, handing the work back to Webpack. The job of webpack/hot/dev-server is to decide whether to refresh the browser or hot update the module based on the information passed to it by webpack-dev-server/client and the configuration of dev-server. Of course, if you just refresh the browser, there are no further steps.

  6. HotModuleReplacement runtime is the centre of the client HMR, step on it receives hash value passed to his new module, it through JsonpMainTemplate. Runtime sends an Ajax request to the server end, The server returns a JSON that contains the hash values of all the modules to be updated. Once the updated list is retrieved, the module requests the latest module code again via JSONP. These are steps 7, 8 and 9 in the figure above.

  7. In step 10, the HotModulePlugin will compare the old and new modules and decide whether to update the module. After the decision is made, the dependency relationship between the modules will be checked and the dependency references between the modules will be updated.

  8. As a final step, when HMR fails, we fall back to live Reload, which is a browser refresh to get the latest packaging code.

Ran Sixi: Webpack HMR principle analysis