What does docType do?

Declare the document type and tell the browser what document standards to use to parse the document:

  • Weird mode: The browser parses the document using its own mode, which defaults to weird mode when doctype is not added
  • Standard mode: Browsers parse documents using W3C standards

What’s the difference between href and SRC

Href (hyperReference) : when the browser encounters href, it downloads resources in parallel without blocking page parsing. For example, when we use to import CSS, the browser downloads CSS in parallel without blocking page parsing. Therefore, we recommend using instead of @import when importing CSS

<link href="style.css" rel="stylesheet" />
Copy the code

SRC (Resource) is a resource. When the browser encounters SRC, it suspends page parsing until the resource has been downloaded or executed, which is why the script tag is placed at the bottom

<script src="script.js"></script>
Copy the code

What properties does meta have and what does it do

Meta tags are used to describe meta information, such as website author, description, and keywords. Meta defines information in the form of name= XXX and Content = XXX. Common Settings are as follows:

  • Charset: Defines the character set for an HTML document
 <meta charset="UTF-8" >
Copy the code
  • Http-equiv: Can be used to simulate HTTP request headers, set expiration time, cache, refresh
<meta http-equiv="expires" content="Wed, 20 Jun 2019 22:33:00 GMT" />
Copy the code
  • Viewport: the viewport is used to control the page width, height and zoom ratio
<meta 
    name="viewport" 
    content="width=device-width, initial-scale=1, maximum-scale=1"
>
Copy the code

What are the parameters of viewPort and what do they do

  • Default width: 980px
  • Initial-scale: indicates the initial scaling ratio, ranging from 1 to 10
  • Maximum-scale /minimum-scale, the maximum /minimum scale that allows the user to scale
  • User-scalable, user scalable (yes/no)

The function and parameters of the http-equive property

  • Expires: Specifies an expiration time
  • Progma: no-cache disables caching
  • Refresh refresh periodically
  • Set-cookie: the cookie can be set
  • X-ua-compatible, using the browser version
  • Apple-mobile-web-app-status-bar-style: Hides the status bar or sets the status bar color for the WebApp full-screen mode

BFC

Simply put, A BFC is an isolated and independent container on a page that is not subject to interference or interference from the outside world

Conditions that trigger the BFC

  • The root element or any other element containing it
  • Float element (element’sfloatnotnone)
  • Absolute positioning element (element haspositionabsolutefixed)
  • Inline block (element hasdisplay: inline-block)
  • Table cells (elements havedisplay: table-cell, default HTML table cell properties)
  • Table title (element hasdisplay: table-caption, HTML table title default property)
  • withoverflowAnd the value is notvisibleThe block element
  • Elastic boxes (flexorinline-flex)
  • display: flow-root
  • column-span: all

What are the rendering rules of the BFC

  • A BFC is a separate container on a page that is isolated from outside interference or interference with the outside world
  • When calculating the height of the BFC, floating child elements also participate in the calculation (i.e. height collapse does not occur with floating elements inside).
  • The region of the BFC does not overlap with the element region of float
  • The elements inside the BFC are placed vertically
  • Margins of two adjacent elements in the BFC will overlap

BFC application scenarios

  • Clear float: Float elements inside the BFC participate in height calculations, so they can be used to clear floats and prevent height collapses
  • Avoid an element being overwritten by a floating element: the region of the BFC does not overlap the region of the floating element
  • Prevent margin overlap: Margins of two adjacent boxes belonging to the same BFC will be folded, but not of different BFC

Refluxing and repainting

Return:

Triggering conditions:

Backflow occurs when changes to the DOM structure cause the DOM geometry to change.

For example, the following operations trigger backflow:

  1. The geometry of a DOM element changes. Common geometry properties arewidth,height,padding,margin,left,top,borderWait, that’s easy to understand.
  2. Make the DOM node happenIncrease or decreaseormobile.
  3. Read and writeoffsetThe family,scrollandclientIn order to retrieve these values, the browser needs to perform a backflow operation.
  4. callwindow.getComputedStyleMethods.

Backflow process: Since the STRUCTURE of the DOM has changed, it is very expensive to start from the DOM generation step, re-calculate the style, generate the layout tree, build the layer tree, and then generate the drawing list and display the entire rendering process.

Redraw:

Triggering conditions:

Repaint occurs when DOM changes result in style changes that do not affect geometry properties.

Redrawing process: Since there is no change in DOM geometry attributes, the location information of elements does not need to be updated. Therefore, when redrawing occurs, the stage of survival layout tree and layer tree establishment will be skipped, and the drawing list will be directly generated, and then the following series of operations such as partition and bitmap generation will continue.

How to avoid triggering backflow and redraw:

  1. Avoid using style too often, and instead modify itclassThe way.
  2. Apply the animation effect topositionProperties forabsoluteorfixedOn the element of.
  3. You can also set the element firstdisplay: none, and then display it after the operation. Because in thedisplayProperties fornoneDOM operations on the element do not cause backflow and redraw
  4. usecreateDocumentFragmentPerform batch DOM operations.
  5. For resize, scroll, etc., perform anti-shake/throttling.
  6. Avoid frequently reading properties that cause backflow/redraw, and if you do need to use them more than once, cache them in a variable.
  7. Using CSS 3transform,opacity,filterThese properties can achieve the effect of composition, i.eGPUTo speed up.

What units do you use for CSS on mobile

  • em: The font size is defined based on the font size of the parent. Define length units based on the current font size. Cases of the parentfont-size: 14px, the childfont-size: 1em;forfont-size: 14px;; If length is defined, the font size of the child is if14px, the childwidth: 2em;forwidth: 24px.
  • rem: Base on the font size of the root element. For example,htmlthefont-size: 14px, the child1rem = 14px.
  • %: Based on the width of the parent. Cases of the parentwidth: 200px, the childwidth: 50%; height:50%;forwidth: 100px; height: 100px;
  • Vw and vh: Based on the width and height of the viewport (viewports do not include the browser’s address bar toolbar and status bar). For example, the viewport width is1000px,60vw = 600px;
  • Vmin and vmax:vminFor the currentvwvhA value of the lesser of;vmaxIs the larger value. Viewport width, for example375px, viewport height812px,100vmin = 375px;.100vmax = 812px;

How do I replace HTTP requests with HTTPS in a project

Since I’m wrapping axios in the project, the domain name of each request is also written in the configuration file. There is a baseURL field for storing it, so simply changing this field can replace all HTTP requests with HTTPS.

Of course, I also learned the following:

Replace HTTP requests with HTTPS using meta tags:

<meta http-equiv ="Content-Security-Policy" content="upgrade-insecure-requests">
Copy the code

RequestAnimationFrame?

RequestAnimationFrame is a browser interface for timed loops, similar to setTimeout, that redraw a web page frame by frame. For JS animations, requestAnimationFrame works better than setInterval.

Why is the script tag recommended to be placed under the body?

JS code is executed immediately after loading, and JS code execution blocks the rendering of the page.

Why do script tags block page rendering? Isn’t the rendering thread separate from the JS engine thread?

JS is a single thread, rendering thread will be suspended when we load the content of the script tag, because the SCRIPT tag may manipulate the DOM, so if you load the script tag and render the page at the same time must conflict, therefore, rendering thread (GUI) and JS engine thread are mutually exclusive.

Js runtime mechanism

  1. Js is a single thread running, can only do one thing at a time, this is because JS is a browser scripting language, the purpose is to interact with the user for DOM operation, single thread running can avoid the contradiction of operating the same DOM at the same time

  2. In the single thread of JS, the task is divided into two kinds: one is synchronous task, the other is asynchronous task

  • Synchronization tasks are queued on the main thread and executed in sequence
  • Asynchronous task: does not enter the main thread, but entersevent tableExecute the asynchronous event and put the result callback into the “task queue” when the result is returned.(taskqueue)An asynchronous task is executed only when the task queue notifies the main thread that it is ready to execute
  1. Js code is divided into two stages: compilation stage and execution stage
  • Compilation stage: this stage is done by the compiler to translate code into executable code. This stage is defined by scope rules (function definition, variable declaration ahead).
  • Execution phase: This is done by the engine, the task is to execute executable code (according to the JS runtime mechanism), the context is created during the execution phase
  1. Asynchronous operations in js
  • SetTimeOut and setInterval
  • ajax
  • promise
  • DOM events

CommonJS and ES6 modules

  • CommonJS Modules are run time loaded, ES6 Modules are compile-time output interfaces
  • CommonJS output is a copy of the value; ES6 Modules output references to values, and changes within the output module can affect the reference changes
  • The module path imported by CommonJs can be an expression because it usesrequire()Methods; ES6 Modules can only be strings
  • CommonJS thisPoints to the current module, ES6 ModulesthisPoint to theundefined
  • And ES6 Modules don’t have these top-level variables:arguments,require,module,exports,__filename,__dirname

The first difference is because CommonJS loads an object (that is, the module.exports property) that is generated only after the script runs. An ES6 module is not an object, and its external interface is a static definition that is generated during the code static parsing phase.

Event Loop Indicates the Event Loop

  • Synchronization tasks are executed on the main thread forming an “execution stack”(execution context stack)
  • Asynchronous task entryEvent TableAnd register the callback function in it. When the asynchronous event completes,Event TableMove this function to the task queue outside the main thread
  • Once all synchronization tasks in the “execution stack” are completed, the system reads the “task queue” and gets the corresponding callback function to execute the tasks in the main thread

This process is repeated over and over again. This is called an Event Loop

Macro task or micro task

Asynchronous tasks can be divided into macro tasks and micro tasks. In the asynchronous promise operation, the new promise is put into the main thread for immediate execution, and promise.then is put into the microtask queue.

  • Macro task: overall code script, setTimeOut, setInterval
  • Mincro-task: Promise.then, promise.Nexttick (node)

The order of the event loop: the first loop starts after entering the overall code (macro tasks), then all microtasks are executed, then macro tasks are executed again. In the same event loop. Micro tasks take precedence over macro tasks, and macro tasks are not executed when the micro task is not completed.

Advantages and disadvantages of single threading

  • Advantages: The system is stable and does not cause serious synchronization problems, such as DOM addition by one thread and DOM deletion by another thread
  • Disadvantages: Prone to code blocking

Why does JS need to be asynchronous

If asynchrony is not present in JS, it can only be executed from top to bottom, and if the previous line takes too long to parse, the following code will be blocked. For users, blocking means “stuck,” which leads to a poor user experience. For example, if you make an Ajax request and you don’t return data, the code behind it can’t execute

Check if it’s an array

  • Array.isArray(arr)
  • Object.prototype.toString.call(arr) === '[Object Array]'
  • arr instanceof Array
  • array.constructor === Array

The difference between mouseover and MouseEnter

  • Mouseover: Events are triggered when the mouse moves over an element or its child, so there is a repetitive, bubbling process. The corresponding remove event is mouseout
  • Mouseenter: When the mouse removes the element itself (any child element that does not contain the element), it triggers an event that does not bubble. The corresponding remove event is mouseleave

Event delegation and bubbling principles

Brief introduction: Event delegate refers to setting listeners on its parent element instead of the event location (dom). Through event bubbling, the parent element can listen to the event triggered on the child element and make different responses by determining the type of dom of the event occurrence element.

For example: the most classic is ul and LI tag event monitoring, for example, when we add events, we use the event delegate mechanism, not directly on the LI tag, but on the UL parent element.

Benefits: Suitable for binding dynamic elements, new child elements can also have listener functions, can also have event triggering mechanism.

Practical application of the event broker in the capture phase

You can prevent events from propagating to child elements at the parent element level, or you can perform certain operations on behalf of child elements.

Implementing an Ajax

Var XHR = new XMLHttpRequest() // The onreadyStatechange event handler must be specified before calling open() to ensure cross-browser compatibility xhr.onreadyStatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status ==== 304) { Console. log(xhr.responseText)} else {console.log('Error:' + xhr.status)}}} '/ API /getSth', true) // The parameter is the data sent as the request body xhr.send(null)Copy the code

Introduce the features, pros and cons of promise, and how it is implemented internally

1) Promise has three states: Pending, which is a pity, and rejected(which has failed).

2) Promise

  • ① Unified asynchronous API

    • One important benefit of Promise is that it will increasingly be used as an asynchronous API for browsers, unifying the various apis and incompatible patterns and approaches that exist today.
  • ②Promise v. event

    • Promises are better suited to dealing with one-time results than events. It is ok to register the callback before or after the result is calculated and get the correct value. This Promise advantage is natural. However, you cannot use promises to handle events that are triggered more than once. Chained processing is another advantage of promises, but events cannot be chained in this way.
  • ③Promise vs. callback

    • The problem of callback hell is solved by expressing asynchronous operations as a flow of synchronous operations.
  • ④ Promises have the added benefit of including better error handling (including exception handling) and being easier to write (because you can reuse synchronous tools like array.prototype.map ()).

3) Disadvantages

  • 1. You cannot cancel a Promise. Once a Promise is created, it will be executed immediately.
  • 2. If you don’t set a callback function, errors thrown inside a Promise won’t be reflected outside.
  • 3. When in the Pending state, there is no way to know what stage of progress is currently in (just started or nearly completed).
  • 4. By the time the Promise actually performs the callback, the part that defines the Promise is actually gone, so the Promise’s error stack context is not very friendly.

4) Simple code implementation The simplest Promise implementation has seven primary properties: State, value, Error, resolve, Reject, and then.

function myPromise(constructor){ let self=this; Self. status="pending" self.value=undefined; Self. reason=undefined; Function resolve(value){// Two ==="pending", If (self.status==="pending"){self.value=value; self.status="resolved"; If (self.status==="pending"){self.reason=reason; if(self.status==="pending"){self.reason=reason; self.status="rejected"; Constructor (resolve,reject); }catch(e){ reject(e); } } myPromise.prototype.then=function(onFullfilled,onRejected){ let self=this; switch(self.status){ case "resolved": onFullfilled(self.value); break; case "rejected": onRejected(self.reason); break; Var p=new myPromise(resolve,reject){resolve(1)}); Function (x){console.log(x)}Copy the code

The specific process of bubbling and capturing

Bubbling means that when an event is bound to a target element, that event will be triggered in turn in its parent element (if the parent element also has the same event, such as when the child element and parent element are both bound with click events).

Capture is passed from top to bottom, as opposed to bubbling.

(Very easy to remember, if you think of a bubble at the bottom of the water that’s coming up from below, so it’s bubbling)

Take a look at this example:

<! Button li ul --> <ul onclick="alert('ul')"> <li onclick="alert('li')"> <button Onclick ="alert('button')"> click </button> </li> </ul> <script> window.addeventListener ('click', Function (e) {alert (' window ')}) document. The addEventListener (' click ', function (e) {alert (' document ')}) < / script > duplicate codeCopy the code

Button > Li > ul > document > window

Window > document > ul > Li > Button

What you think about closures, why closures? Talk about closures and how they work

What is a closure

The result is an inner function that is referenced by an outer variable. If the inner function holds a variable in the scope of the executing function, a closure is formed.

You can access the outer function scope from the inner function. With closures, one can read variables in a function, and two can store variables in a function in memory, protecting them from contamination. Because closures store variable values in functions in memory, it will consume internal storage, so do not abuse closures, otherwise it will affect web page performance, resulting in memory leaks. To free memory when closures are not needed, assign the variable of the inner function object to NULL.

advantages

  1. A variable in the scope of an external function can be accessed from an inner function, and the accessed variable is permanently stored in memory for later use
  2. Avoid variables contaminating the whole world
  3. Store variables in separate scopes as private members

disadvantages

  1. This has a negative impact on memory consumption. Because internal functions hold references to external variables, they cannot be garbage collected and increase memory usage, so improper use can lead to memory leaks
  2. It has a negative impact on processing speed. The hierarchy of closures determines the length of the scope chain through which referenced external variables are searched
  3. You may have captured unexpected values.

Application scenarios

Application Scenario 1: Module encapsulation is a typical application. Before the emergence of module specifications, variables are used in this way to prevent global contamination.

Application Scenario 2: Create a closure in a loop to prevent unexpected values.

This points to the

How many ways does this point to

  • 1. Default binding: In a global environment, this is bound to window by default.

  • 2. Implicit binding: Generally, when called by a function contained in a direct object, also known as a method call, this is implicitly bound to that direct object.

  • 3. Implicit loss: Implicit loss refers to the loss of the binding object of the implicitly bound function so that it is bound to the Window by default. Explicit binding: Binding objects to this using the call(), apply(), and bind() methods is called explicit binding.

  • 4. New binding: If a function or method call is preceded by the keyword new, it constitutes a constructor call. For this binding, it is called a new binding.

    • Constructors usually do not use the return keyword; they usually initialize new objects and return explicitly when the body of the constructor is finished executing. In this case, the constructor call expression evaluates to the value of the new object.
    • If the constructor uses a return statement without specifying a return value, or if it returns a primitive value, the return value is ignored and the new object is used as the result of the call.
    • If the constructor explicitly returns an object using a return statement, the value of the calling expression is that object.

Change the pointer to this inside a function.

  • 1. Apply: Calls a method on an object that replaces the current object with another. B. ply(A, arguments); The method that object A applies to object B.
  • 2. Call: Calls a method on an object that replaces the current object with another. For example, b. call(A, args1,args2); That is, the method that object A calls object B.
  • 3. Bind takes the same arguments as call, except that it returns a function.

Arrow function

  • 1. Arrow functions do not have this, so we need to find the value of this by searching the scope chain. This means that if the arrow function is contained by a non-arrow function, this is bound to the nearest non-arrow function’s this.
  • 2. Arrow functions do not have their arguments objects, but can access arguments objects of peripheral functions
  • 3. It cannot be called by the new keyword, nor does it have a new. Target value or prototype

What does the new operator do

Calling a constructor with the new operator actually goes through the following four steps:

  • Create a new object;
  • Assign the constructor’s scope to the new object (so this refers to the new object);
  • Execute the code in the constructor (add attributes to the new object);
  • Returns a new object.
  • Associates the constructor’s prototype to the instance’s __proto__

inheritance

  • 1, the prototype chain inheritance, the instance of the parent class as a subclass of prototype, his characteristic is the instance is a subclass instance is also the parent class instance, parent of new prototype methods/properties, subclasses can access, and prototype chain inheritance simple and easy to implement, the disadvantage is that all attributes from the prototype object instance Shared by all, unable to realize multiple inheritance, to the parent class constructor arguments.
  • 2. Construct inheritance, using the constructor of the parent class to enhance the instance of the child class, that is, copy the instance attributes of the parent class to the child class, construct inheritance can pass parameters to the parent class, can achieve multiple inheritance, by calling multiple parent class objects. However, the construction inheritance can only inherit the instance attributes and methods of the parent class, not the prototype attributes and methods, and cannot realize the function taking. Each subclass has a copy of the instance functions of the parent class, which affects the performance
  • 3, instance inheritance, for the parent class instance to add new features, as a subclass instance return, the characteristics of instance inheritance is not limited to call methods, whether new subclass () or subclass () return object has the same effect, the disadvantage is that the instance is an instance of the parent class, not the instance of the subclass, does not support multiple inheritance
  • 4, copy inheritance: Features: support multiple inheritance, disadvantages: low efficiency, high memory footprint (because to copy the attributes of the parent class) can not get the parent class is not enumerable methods (not enumerable methods, can not use for in access)
  • 5. Composite inheritance: Inherit the attributes of the parent class and retain the advantages of passing parameters by calling the parent class construction, and then reuse functions by using the parent class instance as the prototype of the subclass
  • 6, parasitic combination inheritance: through the parasitic way, cut off the instance attributes of the parent class, so that when calling the construction of the parent class twice, the two instance methods/attributes will not be initialized, to avoid the shortcomings of combination inheritance

The process of a web page from entering a URL to rendering

  • Enter a URL in your browser
  • Resolve a domain name into an IP address using DNS. A domain name is just a mapping to an IP address. Domain name resolution is the process of restoring a domain name to an IP address. (If an IP address is entered, this step is omitted.)
  • Based on the resolved IP address and port, the browser initiates an HTTP request
  • The browser establishes a TCP connection with the server (setup: three-way handshake)
  • After establishing a connection through TCP’s three-way handshake, the browser sends an HTTP request to the server, requesting a packet
  • The server receives and processes the HTTP request, searches for resources according to the request information, and returns the response information
  • The browser receives the HTTP response
  • If the status code in the message indicates that the request was successful, the returned resource (such as an HTML file) is accepted. At this point, the browser has taken an HTML document and begins parsing it to render it.
  • At this point, the browser takes an HTML document and begins parsing it to render it.
  • HTML parser –> DOM Tree
  • CSS parser –> Style Tree
  • Combine DOM tree and style tree to generate render tree
  • The page is completely rendered.
  • Four waves shut down the TCP connection.

A few words about Http caching

Caching is a very important part of performance optimization, and the browser caching mechanism is also a very important knowledge for development. The following three parts explain the browser caching mechanism:

  • Strong cache
  • Negotiate the cache
  • The cache location

Strong cache

The server notifies the browser of a Cache time (HTTP/1.0 used Expires, whereas HTTP/1.1 used cache-control), and within that time, the next request is made directly to the Cache, and beyond that time, a comparative Cache policy is executed. (This seems fine and reasonable, but there is a potential pitfall: the server time and the browser time may not be the same, so the expiration date returned by the server may be inaccurate. This approach was quickly abandoned in later HTTP1.1 releases.)

Negotiate the cache

After strong cache invalidation, the browser sends a request to the server with a corresponding cache tag in the request header. The server decides whether to use the cache based on this tag, which is called negotiated cache.

The cache location

As mentioned earlier, we fetch resources directly from the cache when a strong cache hit or a negotiated cache returns 304. So where exactly do these resources cache?

There are four cache locations in the browser, in descending order of priority:

  • Service Worker: A Service Worker borrows the idea of a Web Worker, that is, JS runs outside the main thread and cannot be accessed directly because it is out of the browser’s windowDOM. That said, it still helps us accomplish many useful functions, such asOffline caching,Being pushedandNetwork proxy, and other functions.
  • Memory Cache: Refers to the Memory Cache, which is the fastest in terms of efficiency. But it is the shortest in terms of lifetime, and when the rendering process is finished, the memory cache is gone.
  • Disk Cache: The Cache stored on Disk. It is slower than memory Cache in terms of access efficiency, but it has advantages in terms of storage capacity and storage duration. A little bit computer based should make a lot of sense, but I won’t expand it.
  • Push Cache: This is the last line of defense for the browser Cache. It is aHTTP/2HTTP/2, although not currently widely used, is becoming more widely used as HTTP/2 becomes more widely used.

What is the difference between HTTP/1.0 and HTTP/1.1

  • Long connection: HTTP/1.1 supports the pipeline of long connections and requests. Multiple HTTP requests can be sent over a TCP connection, avoiding the time consumption and delay caused by establishing TCP connections for multiple times
  • Cache processing:HTTP / 1.1 introducedEntity Tag, if-unmodified-since, if-match, if-none-matchTo control the cache, see the browser Cache section
  • Bandwidth optimization and network connection usage: HTTP1.1 introduces the range header in the request header to support breakpoint continuation
  • Host header processing: in HTTP/1.0, each server has a unique IP address, but with the development of virtual Host technology, multiple hosts share an IP address is increasingly common, HTTP1.1 request message and response messages should support the Host header field, and the request message if there is no Host header field will be 400 errors

Introduce the new HTTP/2.0 features

  • Multiplexing: The simultaneous completion of multiple requests over a SINGLE TCP connection
  • Server push: The server can actively push resources to the client
  • New binary format: HTTP/2 transmits data in binary format, which is more analytical and extensible than HTTP/1.1’s text format
  • Header compression: HTTP/2 compresses the header, reducing the size of the transmitted data

Talk about the fundamentals of HTTP/2.0 multiplexing and the problems it solves

HTTP/2 addresses the same problem HTTP/1.1 has:

  • TCP slow start: After the TCP connection is established, it will go through a slow start and then fast send process, just like the start of a car. If our webpage files (HTML/JS/CSS/icon) all go through a slow start, the performance is not a small loss. In addition, slow start is a TCP policy to reduce network congestion, which we cannot change.
  • Multiple TCP connections compete for bandwidth: Multiple TCP connections compete for bandwidth when the bandwidth is insufficient, affecting the download of key resources.
  • HTTP/1.1 queue header blocking: Although HTTP/1.1 long links can transmit multiple requests over a TCP connection, only one request can be processed at a time, and other requests can be blocked until the current request is completed.

To solve these problems, HTTP/2 uses only one TCP long connection per domain name to transfer data, and requests are directly parallel and non-blocking, which is multiplexing

Implementation principle: HTTP/2 introduces a binary frame splitting layer. When the client and server transmit data, the data will be processed by the binary frame splitting layer first and converted into frames with request ID one by one. These frames are combined into corresponding data according to THE ID after transmission.

Tell me about HTTP / 3.0

Although HTTP/2 solves many of the problems of 1.1, HTTP/2 still has some defects. These defects are not from HTTP/2 itself, but from the underlying TCP protocol. We know that TCP links are reliable connections. HTTP/1.1 can use up to six TCP connections at the same time, with one blocking and the other five still working, but HTTP/2 has only one TCP connection, which magnifies the blocking problem.

Because TCP protocol has been widely used, it is difficult to modify TCP directly. Based on this, HTTP/3 chooses a compromise method — UDP protocol. HTTP/2 implements multiplexing, 0-RTT, TLS encryption, traffic control, packet loss and retransmission on the basis of UDP.

What is the difference between HTTP and HTTPS

  • HTTPS uses port 443, while HTTP uses 80
  • HTTPS requires a certificate
  • HTTP is hypertext transfer protocol, is plaintext transfer; HTTPS is the ssl-encrypted protocol, which is more secure for transmission
  • HTTPS is slower than HTTP because HTTPS adds nine packets for the SSL handshake in addition to the three packets for the TCP handshake

What is MVVM?

MVVM is short for Model-view-ViewModel, which is the evolution of Controller from MVC to ViewModel. The Model layer represents the data Model, the View represents the UI component, and the ViewModel is the bridge between the View and the Model layer. The data will be bound to the ViewModel layer and automatically rendered to the page. The ViewModel layer will notify the ViewModel layer to update the data when the View changes.

A brief description of the principle of Vue2. X responsive data

When Vue initializes data, it redefines all attributes in data using Object.defineProperty. When the page uses the corresponding attribute, dependency collection is first performed (the watcher of the current component is collected). If the attribute changes, dependencies are notified to update (publish subscribe).

Vue3. X Responsive data principle

Vue3. X uses Proxy instead of Object.defineProperty. Because proxies can listen directly for changes in objects and arrays, there are as many as 13 interception methods. And as a new standard, browser vendors will continue to focus on performance optimization.

Proxy only proxies the first layer of an object, so how does Vue3 handle this?

Check if reflect. get is Object, and reactive is used to proxy it.

It is possible to get/set multiple times while monitoring arrays, so how do you prevent multiple get/set triggers?

We can determine whether key is the property of the current proxied object target itself or whether the old value is equal to the new value. Trigger can be executed only when one of the above two conditions is met.

How to monitor array changes in vue2. X

Using the method of function hijacking, rewrite the array method, Vue will be in the data array prototype chain rewrite, pointing to their own definition of the array prototype method. This allows dependency updates to be notified when the array API is called. If the array contains a reference type, a recursive traversal of the array is monitored. This allows you to monitor array changes.

How does nextTick work

The nextTick batch asynchronous update strategy, in a nutshell, executes a deferred callback after the next DOM update cycle ends. It is mainly aimed at solving: For example, if a change in data causes a view to be updated, and if it’s changed many times in a short period of time, say 1,000 times, and each change triggers the setter in the data and runs down the process until the real DOM is changed, then the DOM will be updated 1,000 times, That would certainly be very inefficient.

The browser platform does not implement the nextTick method, so the ue. Js source code uses Promise, setTimeout, setImmediate, etc., to define an asynchronous method, nextTick, which receives a callback. Multiple calls to nextTick queue incoming callbacks, execute those just stored in the queue when the current stack is complete, and empty the current queue using the asynchronous method.

Why is data in a component a function?

When a component is reused multiple times, multiple instances are created. Essentially, these instances all use the same constructor. If data is an object, the object is a reference type that affects all instances. So to ensure that data does not conflict between different instances of the component, data must be a function.

Let’s talk about how the V-Model works

The V-model is essentially a syntax sugar, which you can think of as the syntax sugar of the value + input method. This can be customized through the Prop and Event properties of the Model property. The native V-Model generates different events and attributes depending on the tag.

  • Text and Textarea elements are usedvalueProperties andinputEvents;
  • Checkbox and radio usecheckedProperties andchangeEvents;
  • The select field willvalueAs prop and willchangeAs an event.

Here’s how Vue event binding works

Native event bindings are bound to real elements via addEventListener, and component event bindings are implemented via Vue’s custom $on.

In other words: Vue supports two event types, native DOM events and custom events.

  1. ordinaryDOMAnd components are hung.nativeAfter the modifier, the final call is still nativeaddEventListener()methods
  2. Components,VueThe event on the instance calls the event on the prototype$on, $emit, $off, $onceMethods.

How does Vue template compile?

The Vue template compilte stage, which translates the Template to render function, goes through the following three stages:

  1. parsePhase willtemplateStrings generate an abstract syntax tree through various regular expressionsASTIn the parsing process is throughwhileIterate over the string, moving down each label pointer after parsing; A stack is also used to establish a hierarchy between nodes, that is, to hold the parsed tag headers.
  2. optimizePhase will generate an abstract syntax treeASTFor static marking, the nodes marked as static are in the followingpatchComparison will be skipped during the process, so as to achieve the purpose of optimization. The main process of tagging is to set up for each node similar tostaticOr set one for the root nodestaticRootProperty indicates whether this is a static root.
  3. In into thegeneratePhase, indicating that statically marked values have been generatedASTAnd thegenerateIs toASTintorender functionA string.

The diff algorithms for Vue2. X and Vue3. X renderers are described separately

In simple terms, the diff algorithm has the following process

  • Compare siblings first and then children
  • First determine whether one party has child nodes or one party has no child nodes. If the new party has child nodes and the old party does not, the new child node replaces the original node. Similarly, if the new party does not have children and the old party does, it is equivalent to deleting the old node.
  • Let’s compare the situation where we both have childrendiffThe core of the. I’m going to judge the two nodes firstKey, tag, isComment, and data are defined or not defined at the same time, and type is different when the tag type is inputTo determine whether the two nodes are the same, and if not, to replace the old node with the new one.
  • It’s only entered if it’s the same nodepatchVNodePhase. At this stage, the core is to use the algorithm of double-end comparison, which compares the old and new nodes at both ends at the same time. In this process, static mark coordination during template compilation will be usedkeyTo skip comparing static nodes, and if not, do other comparisons.

Vue3. X draws on ivI algorithm and Inferno algorithm

The type of VNode is determined when VNode is created, and the bit operation is used to determine the type of a VNode in the process of mount/patch. On this basis, combined with the core Diff algorithm, the performance is improved compared with Vue2. (The actual implementation can be viewed with Vue3. X source code.)

The algorithm also uses the idea of dynamic programming to solve the longest recursive subsequence.

The virtual Dom and the role of the key attribute

Because DOM manipulation in a browser is expensive. Frequent DOM manipulation can cause performance problems. This is where the virtual Dom comes in.

Vue2’s Virtual DOM is based on the open source library SNabbDOM.

The essence of Virtual DOM is to use a native JS object to describe a DOM node. Is a layer of abstraction from the real DOM. (This is the VNode class in the source code, which is defined in SRC /core/vdom/vnode.js.)

VirtualDOM mapping to the real DOM goes through the create, diff, and Patch stages of a VNode.

“The key’s job is to reuse as many DOM elements as possible.”

Only when the order of the nodes is different between the old and new children should the best action be to update the elements by moving them around.

The mapping needs to be saved in the old and new children’s nodes so that reusable nodes can be found in the old children’s nodes. Key is the unique identifier of a node in children.

What Vue performance optimizations have you done?

Coding phase

  • Minimize the amount of data in data. Getter and setter are added to all data in data, and the corresponding Watcher is collected
  • V-if and V-for cannot be used together
  • Use the event broker if you need to use V-for to bind events to each element
  • The SPA page uses the keep-alive cache component
  • In more cases, use v-if instead of V-show
  • Key guarantees uniqueness
  • Use routing lazy load, asynchronous components
  • Anti-shake and throttling
  • Import third-party modules as required
  • Long lists scroll to visual area for dynamic loading
  • Lazy loading of images
  • Some common methods are packaged as library and published to NPM, then referenced in multiple projects
  • Some common components will also be packaged into a separate project and then published to NPM \ using Webpack

SEO optimization

  • pre-rendered
  • Server rendering SSR

Packaging optimization

  • The compression code
  • Tree Shaking/Scope Hoisting
  • Load third-party modules using CDN
  • Multithreaded package Happypack
  • SplitChunks removes public files
  • SourceMap optimization

The user experience

  • Use loading or skeleton screen
  • PWA
  • Encapsulate an SVG component to use iconfont color ICONS to enrich pages

You can also use caching (client-side caching, server-side caching) optimization, server-side gZIP compression, and so on.

Difference between hash mode and history mode in Vue

  • The most obvious is in the display,hashPatterns ofURLIt’s going to be mixed in#Number, andhistoryNo.
  • VueThey are implemented differently at the bottom.hashPatterns depend ononhashchangeEvent (listeninglocation.hashChange), whilehistoryPatterns are primarily dependentHTML5 historyThe two new methods in thepushState()You can changeurlAddresses and doesn’t send requests,replaceState()You can read the history stack and modify the browser record.
  • When really need to passURLSend back endHTTPRequest time, such as the common user manual inputURLPress Enter, or refresh (restart) the browserhistoryPatterns require support from the back end. becausehistoryIn mode, front-endURLMust send the request to the actual backendURLAgree, for example there is oneURLIs with a pathpath(i.e.www.lindaidai.wang/blogs/id) if the path is not processed by the back end404Error. Therefore, the backend needs to add a candidate resource that covers all cases, usually in conjunction with the one given by the front-end404Page.

hash:

Window.onhashchange = function(event){// location.hash "#heading-3" // So let hash = location.hash. Slice (1); }Copy the code

Does the write name option in the Vue component do anything other than match keep-alive? Can you talk about what you know about Keep-alive?

What is the use of the name option in the component?

  • Projects usingkeep-alive, can be matched with componentsnameCache filtering
  • DOM calls itself when it’s a recursive componentname
  • vue-devtoolsThe group names displayed in the debugger are determined by the component name in vUE

Keep -alive

  • keep-aliveVue is a built-in component that allows contained components to remain in state and avoid re-rendering
  • It is used together with routing and dynamic components to cache components.
  • provideincludeexcludeProperty, both of which support strings or regular expressions,includeIndicates that only components with matching names will be cached,excludeIndicates that any component whose name matches will not be cached, whereexcludePriority ratio ofincludeHigh;
  • There are two hook functionsactivateddeactivatedWhen the component is activated, the hook function is triggeredactivatedTriggers the hook function when a component is removeddeactivated.

Why does Vue use vm.$set() to solve the problem that new object attributes cannot respond? Can you explain how the following code works?

Vue.set (object, propertyName, value) 
vm.$set (object, propertyName, value)
Copy the code

Why does Vue use vm.$set() to solve the problem that new object attributes cannot respond

  • Vue usedObject.definePropertyImplement two-way data binding
  • Executes on properties when initializing instancesgetter/setterconversion
  • A property must exist on a data object for Vue to convert it to responsive (which makes it impossible for Vue to detect the addition or deletion of an object property)

$set (object, propertyName, value)/vm.$set (object, propertyName, value)

What about the implementation of the framework itself?

Vue source location: Vue/SRC/core/instance/index. Js

export function set (target: Array<any> | Object, key: any, val: any): Any {// target isArray if (array.isarray (target) &&isvalidarrayindex (key)) { Target.length = math.max (target.length, key) // Use the array splice method to trigger the response target.splice(key, 1). Val) return val} if (key in target &&! (key in Object.prototype)) { target[key] = val return val } const ob = (target: Any).__ob__ // Target itself is not a response data, directly assigned if (! Ob) {target[key] = val return val} defineReactive(ob.value, key, val) ob.dep.notify() return val}Copy the code

$set vm.$set vm.$set

  • If the target is an array, use the arrayspliceMethod triggers corresponding expression;
  • If the target is an object, it first checks whether the property exists and whether the object is reactive.
  • Ultimately, if you want to respond to a property, it’s through a calldefineReactiveMethod for reactive processing

DefineReactive is what Vue calls when it initializes an Object and dynamically adds getters and setters to Object properties using Object.defineProperty

Since Vue can accurately detect changes in the specific DOM through data hijacking, why do you need virtual DOM diff?

Pre-knowledge: dependency collection, virtual DOM, responsive systems

Modern front-end frameworks detect change in two ways: pull and push

pull: React. Remember how React detects changes. We usually use the setStateAPI to explicitly update things. React doesn’t know exactly what’s changed from the start, only that “it’s changed” and then performs a violent Diff operation to find “what’s changed”. Another example is Angular’s dirty check operation.

Push: The responsive system of Vue is the representative of push. When the Vue program is initialized, it will collect data depending on it. Once the data changes, the responsive system will know immediately. So Vue knows “where the change happened” from the start, but this creates a problem. If you’re familiar with Vue’s responsive systems, you usually need a Watcher to bind each data. Right

Once our binding is too fine-grained, we can generate a lot of Watcher, which incurs memory and dependency tracing overhead, And fine-grained too low can’t accurately detect changes, so the design of the Vue is to choose the medium fine-grained scheme, push in component level detection way, also is the set of responsive system, usually we will detect changes in the first time the component, then inside the component Virtual Dom Diff to obtain more specific differences, While Virtual Dom Diff is a pull operation, Vue is a combination of push and pull for change detection.

The HTTP status code

1xx indicates that the client should continue sending the request

2xx indicates a successful request

  • 200 indicates OK. Information is returned normally
  • 201 indicates that the request succeeds and the server creates a new resource
  • 202 indicates that the server has accepted the request but has not yet processed it

3xx indicates redirection

  • 301 indicates a permanent redirect. The requested page has been permanently moved to a new location
  • 302 indicates a temporary redirect
  • 304 indicates that the content of the page has not changed since the last request

4xx indicates a client error

  • 401 indicates that the server does not understand the format of the request
  • 402 indicates that the request is not authorized
  • 403 indicates that access is prohibited
  • 404 indicates that the requested resource does not exist

5xx indicates a server error

  • 500 represents the most common server errors
  • 503 indicates that the server is temporarily unable to process the request