2023 Ultra-Comprehensive Front-end Interview Questions - Memorize them and you will be sure to get an offer (welcome additions)

HTML, CSS related

HTML5

HTML5 new features

  1. The form has been enhanced, and some new input types have been added:

    color----define color palette

    tel-----define an input field containing a phone number

    email—defines an input field containing an email address

    search – define search domain

    number – defines an input field containing a numerical value

    date----define the input field for selecting day, month and year

  2. Video tag;

  3. Audio audio tag;

  4. Semantic tag; datatime-local

  5. Defines the abbreviation for the document type

  6. Geolocation;

  7. Drag and drop API;

  8. Canvas graphics drawing;

  9. rich text

  10. Web Storage:

localStorage: data storage without time limit
sessionStorage: will be cleared when the browser is closed

Semantic tags

The first is the difference between semantics and default styles. Default styles are the expressions of some commonly used tags set by browsers. The main purpose of semantics is to let everyone intuitively understand the use of tags (markup) and attributes (attribute). and function , which obviously looks a lot like the title because of its bold font and larger font size. strong, em are used to distinguish them from other words and play the role of emphasis.

Semantic

Semantic tags: p, strong, em, footer
New semantic tags in HTML5:

  • header
  • nav(navigation)
  • section (mainly used to divide content on pages in websites or applications.)
  • article (a part of a page, and this part is dedicated to independent classification or reuse)
  • aside (define content other than article, the content of aside should be related to the content of article. Indicates the subsidiary information part of the current page or article)
  • footer(bottom)

The advantages of semantics are:

(1) The code structure is clear, easy to read, and conducive to development and maintenance

(2) Facilitate device parsing and render web pages based on semantics

(3) Conducive to (SEO) search engine optimization

(4) When the browser css fails, the page is still readable

How to semanticize:

Do not use pure style tags (b, i, u), use less semantic tags (div, span), and use semantic tags

box model

What is the box model?

CSS Box Model. All HTML elements can be thought of as a box; in CSS, the term Box Model is used in design and layout.

There are currently two known box models, the W3C box model (standard box) and the IE box model (weird box).

What are the W3C box model (standard box) and IE box model (weird box)?

W3C box model, also known as the standard box model

Width = width of content (content) + border + padding + margin

IE box model, also known as weird box model

Width = content width (content+border+padding) + margin

Why is it called IE box model (weird box)?

It's because the boxes in lower versions of IE use border-box. In later IE5.5, IE6 and later, the box model is content-box. Note: When the browser does not set the <!doctype> declaration, the box model is border-box.

The scope of the IE box model also includes margin, border, padding, and content. The difference from the standard W3C box model is that the content part of the IE box model includes border and padding. IE box model box-sizing: border-box.

The box model of an element can be changed through the box-sizing property of CSS3. The scope of the standard W3C box model includes margin, border, padding, and content, and the content part does not include other parts.

box-sizing property?

The parsing mode used to control the element's box model. The default is content-box. Interchange model format.

content-box : W3C's standard box model. Setting the height/width attributes of the element refers to the height/width of the content part.

border-box : IE traditional box model. Setting the height/width attributes of the element refers to the height/width of the border + padding + content part

label element

What are inline elements, block-level elements, and empty elements? the difference?

1. Inline elements: span, a, em, img, input

2. Block-level elements: div, ol, ul, form

3. Empty elements: br, hr, img, input

the difference:

Inline elements do not wrap, block-level elements wrap

Normally, block-level elements contain inline elements. Rarely, inline elements contain block-level elements.

Tags with no content are called empty elements, and empty elements are closed in the opening tag.

cache

The difference between offline caching and traditional browser caching

Offline cache is the entire application, traditional browser cache is a single file

Offline caching allows you to still open pages after disconnecting from the Internet, but traditional browser caching cannot

Offline buffering gives priority to cache when there is a network. Traditional browser cache will notify the network to update the cache.

local storage

Can you talk about the browser's local storage? What are the pros and cons of each?

The browser's local storage is mainly divided into Cookie and WebStorage, of which WebStorage can be divided into localStorage and sessionStorage.

cookie

Cookie data is always carried in HTTP requests from the same origin, that is, the cookie is passed back and forth between the browser and the server. Cookie data cannot exceed 4K.
Cookies are vulnerable to XSS attacks.
If the website does not filter user input, it may cause XSS attacks or be used for CSRF attacks.

localStorage和sessionStorage

These two APIs are new APIs added with HTML5. The main difference between the two is the different timeliness, and the size is 5mb. Mainly stored as strings in the form of key and value.

shortcoming:

The disadvantage of localStorage is that it can only store strings and cannot store objects directly, so we have to re-process json every time we store and retrieve...

As for JSON.stringify(), we know that it cannot handle some types such as undefined funtion normally, and it cannot convert circularly referenced objects, so you need to pay attention when using it.

Common points:

They will all be saved on the browser side, with size and origin restrictions.

difference:
  1. Cookie data is always carried in HTTP requests from the same origin, that is, the cookie is passed back and forth between the browser and the server. sessionStorage and localStorage do not automatically send data to the server, but only save it locally.

  2. Storage size limits are also different: cookie data cannot exceed 4K, sessionStorage and localStorage can reach 5M or more

  3. Different scopes: sessionStorage: valid only until the current browser window is closed; localstorage: the data is always valid, and the window or browser is closed, unless the data is deleted; cookie: valid before the set cookie expiration time, even if the window is closed or Browser close

CSS

CSS style priority

!important>style>id>class

BFC

BFC stands for block formatting context. Elements inside the BFC will not affect elements outside.

create:

1. float is not none

2. position is absolute or fixed

3.overflow is not visible

4.display为inline-block、flex、inline-flex等

application:

  1. Prevent margin overlap

  2. clear internal float

  3. Adaptive multi-column layout

three column layout

Absolute positioning method: use margin/padding in the middle column to clear the left and right positions, and use absolute positioning on the left and right

Floating method: use margin/padding in the middle column to clear the left and right positions, and use floating positioning on the left and right

Flex:flex:1

Grid: Father element: display:grid Child element: grid-template-columns:100px auto 20px

CSS selector

  1. tag selector

  2. ID selector

  3. class selector

  4. Group selector

  5. wildcard selector

  6. descendant selector

  7. Child element selector

  8. Pseudo class selector

What is Flex:1

Often used for adaptive layouts. That is, the abbreviation of flex-grow, flex-shrink, flex-basis

Display: Common properties of flex

flex-direction: Set the spindle direction

Justify-content: Set the main axis arrangement

Flex-wrap: Set whether to wrap or not

Align-content/align-item: cross-axis arrangement (multiple lines/single lines)

Preprocessor less, sass

It is an abstraction layer in CSS. benefit:

1. Clear structure and easy to expand

2. Conveniently shield syntax differences between browsers

3.multiple inheritance

DOM, BOM objects

BOM refers to the browser object model, which can access and operate the browser window. Using the BOM, developers can move windows, change text in the status bar, and perform other actions not directly related to the content of the page.

DOM refers to the Document Object Model, through which all elements of an HTML document can be accessed. DOM is a W3C standard.

Browser rendering mechanism

Web page generation process:

1. HTML is parsed into a DOM tree by the HTML parser

2. css is parsed into a CSSOM tree by the css parser

3.Combine the DOM tree and CSSOM tree to generate a render tree (Render Tree)

4. Generate layout (flow), that is, plane synthesis of all nodes of all rendering trees

5. Draw the layout on the screen

Rearrangement (also called reflow)

When DOM changes affect the geometric information of the element (the position and size of the DOM object), the browser needs to recalculate the geometric properties of the element and place it in the correct position in the interface. This process is called rearrangement. Trigger: adding or removing visible DOM elements, element size changes - margins, padding, borders, width and height

Redraw

When the appearance of an element changes, but the layout is not changed, the process of redrawing the element's appearance is called redrawing. Trigger: Change the color, background, box-shadow and other attributes of the element

Reflow and redraw optimization suggestions

1. The simpler the style sheet, the faster it will reflow and redraw. Use classes as much as possible and less style to change styles one by one.

2. The higher the level of DOM elements that are reflowed and repainted, the higher the cost. If you can flexibly use display, absolute, flex, etc., the rearrangement overhead will be relatively small, or it will not affect the rearrangement of other elements.

3.Script library using virtual DOM.

JS related

js data type, typeof, instanceof

  1. string、number、boolean、null、undefined、object(function、array)、symbol

  2. typeof is mainly used to determine the data type

  3. instanceof determines whose instance the object is.

ES6

  1. The new symbol type represents a unique value and is used to define unique object attribute names;

  2. const/let are used to declare variables, which cannot be declared repeatedly and have block-level scope. There is a temporary dead zone, that is, there is no variable promotion. (const is generally used to declare constants);

  3. Destructuring assignment of variables (including arrays, objects, strings, numbers and Boolean values, function parameters), remainder operator (...rest);

  4. template string(${data});

  5. spread operator(array, object);;

  6. arrow function;

  7. Set and Map data structures;

  8. Proxy/Reflect;

  9. Promise

Symble in ES6

It functions like a unique ID that is unique to each Symbol instance. Symbol type keys cannot be enumerated through Object.keys() or for...in, and they are not included in the object's own property names. Therefore, using this feature, we can use Symbol to define some properties that do not require external operations and access.

Set and map in ES6

Map objects store key-value pairs. Any value (object or primitive) can be used as a key or a value. The constructor Map can accept an array as a parameter.
Set objects allow you to store any type of value, whether a primitive value or an object reference. It is similar to an array, but the values ​​of the members are unique and there are no duplicate values.

vue key

1. The main function of key is to update the virtual DOM efficiently. The principle is that Vue can accurately determine whether two nodes are the same through key during the patch process, thereby avoiding frequent updates of different elements, making the entire patch process more efficient and reducing DOM operations. quantity and improve performance.

2. In addition, if the key is not set, it may cause some hidden bugs when updating the list.

3.In Vue, the key attribute is also used when transitioning elements with the same tag name. The purpose is also to allow Vue to distinguish them. Otherwise, Vue will only replace its internal attributes and not trigger the transition effect.

The difference between ordinary functions and arrow functions

1. The arrow function is an anonymous function and cannot be used as a constructor or new.

2. The arrow function does not bind arguments and uses rest parameters instead...Solution

3.The arrow function does not bind this and will capture the this value of the context in which it is located as its own this value.

4. When the arrow function calls a function through the call() or apply() method, only one parameter is passed in and has no effect on this.

5. Arrow functions cannot be used as generator functions and the yield keyword cannot be used.

Closure

A closure is a function that has access to a variable in the scope of another function. A closure occurs when a function can remember and access the lexical scope it is in, even if the function is executed outside the current lexical scope.

Closure purpose:
to be able to access the lexical scope in which the function is defined (preventing it from being recycled)

privatized variables

Simulating block-level scope

Create module

Disadvantages of closures: will cause the variables of the function to be kept in memory, and too many closures may cause memory leaks.
Prototype, prototype chain (high frequency)
prototype: the inherent __proto__ attribute in the object, which points to the prototype of the object Prototype properties.

Prototype chain: When we access the properties of an object, if the property does not exist inside the object, then it will look for the property in its prototype object. This prototype object will have its own prototype, so it keeps looking. Going on, that is the concept of the prototype chain. The end of the prototype chain is generally Object.prototype, so this is why our newly created objects can use methods such as toString().

Features: JavaScript objects are passed by reference, and each new object entity we create does not have its own copy of the prototype. When we modify a prototype, the objects related to it will also inherit this change.

this-oriented

Represents the current context object. In object-oriented languages ​​this represents a reference to the current object. But in JavaScript this is not fixed, it will change as the environment changes.

  1. In a method, this represents the object to which the method belongs

  2. When used alone, this represents the global object

  3. In a function, this represents the global object

  4. In a function but in strict mode, this is undefined

  5. In an event, this represents the element that receives the event.

Methods such as call and apply can change the apply, call and bind calling modes of the object referenced by this. All three methods can explicitly specify the this pointer of the calling function. Apply accepts an array as parameters, call accepts a parameter list, and the bind method passes in an object.

new keyword

1. First a new empty object is created

2. Set the prototype and set the object's prototype to the function's prototype object.

3.Let the this of the function point to this object and execute the code of the constructor (add attributes to this new object)

4. Determine the return value type of the function. If it is a value type, return the created object. If it is a reference type, an object of this reference type is returned.

scope, scope chain

A scope is responsible for collecting and maintaining a set of queries consisting of all declared identifiers (variables) and enforcing a very strict set of rules that determine the access rights of the currently executing code to these identifiers. (Global scope, function scope, block-level scope). The scope chain is to search for a variable layer by layer starting from the current scope, until the global scope is found and still not found, it is given up. This layer-by-layer relationship is the scope chain.

Inheritance (including es6), multiple inheritance methods

(1) The first is to implement inheritance through a prototype chain, but the disadvantage of this implementation is that when it contains reference type data, it will be shared by all instance objects, easily causing confusion in modifications. Also, parameters cannot be passed to the supertype when creating a subtype.

(2) The second method is to use a borrowed constructor. This method is achieved by calling the supertype constructor in the subtype function. This method solves the shortcoming of not being able to pass parameters to the supertype. , but one of its problems is that it cannot realize the reuse of function methods, and the method subtype defined by the supertype prototype cannot be accessed.

(3) The third way is combined inheritance. Combined inheritance is a way to combine the prototype chain and the borrowed constructor. The inheritance of type attributes is achieved by borrowing constructors, and the inheritance of methods is achieved by setting the prototype of the subtype to an instance of the super type. This method solves the problem when the above two modes are used alone. However, since we use the instance of the super type as the prototype of the subtype, we call the constructor of the super class twice, resulting in the prototype of the subtype. There are many more unnecessary attributes.

(4) The fourth way is prototypal inheritance. The main idea of ​​prototypal inheritance is to create new objects based on existing objects. The principle of implementation is to pass an object into the function and then return an object based on this object. Prototype object. This idea of ​​inheritance is not mainly to create a new type, but to implement a simple inheritance of a certain object. The Object.create() method defined in ES5 is the implementation of prototypal inheritance. The disadvantages are the same as the prototype chain approach.

(5) The fifth way is parasitic inheritance. The idea of ​​​​parasitic inheritance is to create a function to encapsulate the inheritance process, by passing in an object, then copying a copy of the object, then extending the object, and finally returning the object. . This expansion process can be understood as a kind of inheritance. The advantage of this kind of inheritance is to implement inheritance for a simple object, if the object is not our custom type. The disadvantage is that there is no way to reuse functions.

(6) The sixth method is parasitic combined inheritance. The disadvantage of combined inheritance is that using instances of the super type as the prototype of the subtype results in the addition of unnecessary prototype attributes. Parasitic compositional inheritance uses a copy of the supertype's prototype as the subtype's prototype, thus avoiding the creation of unnecessary properties.

EventLoop

JS is single-threaded. In order to prevent a function from taking too long to execute and blocking the subsequent code, the synchronous code is first pushed into the execution stack and executed sequentially. The asynchronous code is pushed into the asynchronous queue. The asynchronous queue is divided into macro task queues. And microtask queue, because the execution time of macrotask queue is longer, so microtask queue has priority over macrotask queue. The representatives of the microtask queue are Promise.then, MutationObserver, and the macrotasks are setImmediate setTimeout setInterval

native ajax

Ajax is an asynchronous communication method that obtains data from the server to achieve the effect of partially refreshing the page. process:

  1. Create an XMLHttpRequest object;

  2. Call the open method and pass in three parameters: request method (GET/POST), url, synchronous and asynchronous (true/false);

  3. Listen to the onreadystatechange event and return responseText when readystate is equal to 4;

  4. Call the send method to pass parameters.

Event bubbling, capturing (delegate)

Event bubbling refers to triggering a certain type of event on an object. If the object is bound to the event, the event will be triggered. If not, it will be propagated to the parent object of this object. Finally, the parent object triggers the event.
Event delegation essentially takes advantage of the browser event bubbling mechanism. Because the event will be uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, the listening function of the child node can be defined on the parent node, and the listening function of the parent node will process multiple child elements uniformly. events, this approach is called an event proxy.
event.stopPropagation() or the method under ie event.cancelBubble = true; //Prevent event bubbling

Vue

A brief introduction to MVVM

MVVM is the abbreviation of Model-View-ViewModel, which is the evolution of Controller in MVC into ViewModel. The Model layer represents the data model, the View represents the UI component, and the ViewModel is the bridge between the View and Model layers. The data will be bound to the viewModel layer and automatically render the data into the page. When the view changes, the viewModel layer will be notified to update the data.

Talk about your understanding of the vue life cycle?

Each Vue instance will go through a series of initialization processes when it is created. The life cycle hook of Vue is a function that is triggered when a certain stage or condition is reached. The purpose is to complete some actions or events.

create phase: The vue instance is created beforeCreate: Before creation, the data in data and methods have not been initialized at this time created: After creation, there are values ​​in data and are not mounted. mount phase: The vue instance is mounted to the real DOM node
beforeMount : You can initiate a server request to get the data mounted: At this time, you can operate the Dom
update phase: when the data data in the vue instance changes, the re-rendering of the component is triggered beforeUpdate updated
destroy phase: the vue instance is destroyed beforeDestroy: before the instance is destroyed, At this time, you can manually destroy some methods. Why is destroyed
data a function instead of an object
? Because the object is a reference data type, if data is an object, all components will share the same data. When data is a function, a new object will be returned after each function is executed. In this case, each component will maintain an independent object (data).

computed and watch

The watch attribute monitor is an object. The key is the attribute that needs to be observed, and the value is the corresponding callback function. It is mainly used to monitor changes in certain specific data, so as to perform certain specific business logic operations. Monitoring attribute changes needs to be performed when the data changes. Used when performing asynchronous or expensive operations

The results of computed computed attributes will be cached. When the attributes that the functions in computed depend on have not changed, the results will be read from the cache when the current function is called. Unless the dependent responsive properties change, they will be recalculated. They are mainly used as properties. Functions in computed must use return to return the final result. computed is more efficient and should be used first.

Usage scenario computed: used when one attribute is affected by multiple attributes, for example: shopping cart product settlement function watch: used when one piece of data affects multiple pieces of data, for example: search data

The role of key in v-for

  1. The main function of key is to more efficiently compare whether each node in the virtual DOM is the same node;

  2. Vue determines whether two nodes are the same node during the patch process. Key is a necessary condition. When rendering a set of lists, key is often a unique identifier. Therefore, if key is not defined, Vue can only think that the two compared nodes are the same. One, even if they are actually not, this results in frequent updates of elements, making the entire patch process less efficient and affecting performance;

  3. It can be known from the source code that when Vue determines whether two nodes are the same, it mainly determines the key and element type of the two nodes. Therefore, if the key is not set, its value is undefined, and it may always be considered that these are two identical nodes. Can perform update operations, which results in a large number of DOM update operations, which is obviously not advisable.

Communication method of vue components

Parent-child component communication

father->child props, child->father on, on,o n and emit 获取父子组件实例 parent、parent、children Ref 获取实例的方式调用组件的属性或者方法 Provide、injectare not officially recommended, but they are commonly used when writing component libraries.

Sibling component communication

Event Bus implements cross-component communication Vue.prototype.$bus = new Vue() Vuex

Cross-level component communication

a t t r s 、 attrs、 attrslisteners Provide、inject

Routing parameters

  1. Use router-link for routing navigation and passing parameters

  2. Directly call $router.push to implement jump with parameters

  3. Determine the matching route through the name in the routing attribute, and pass the parameters through params

  4. Use path to match the route, and then pass parameters through query. In this case, the parameters passed by query will be displayed in the url.

Two modes of routing: hash and history

For progressive front-end development frameworks such as Vue, in order to build a SPA (single page application), a front-end routing system needs to be introduced, which is the meaning of Vue-router. The core of front-end routing is to change the view without sending a request to the back-end.
1. Hash - the # symbol in the URL in the address bar. Its characteristic is that although the hash appears in the URL, it will not be included in the HTTP request and has no impact on the backend. Therefore, changing the hash will not reload the page. .

2. History - takes advantage of the new pushState() and replaceState() methods in the HTML5 History Interface. These two methods are applied to the browser's history station. Based on the current back, forward, and go, they provide the function of modifying the history record. Just when they perform modifications, although the current URL has been changed, your browser will not immediately send a request to the backend. In history mode, 404 will occur and background configuration is required.

route guard

Two-way binding implementation principle
When a Vue instance is created, Vue will traverse the properties of the data option, use Object.defineProperty to convert them into getters/setters and track related dependencies internally, notifying changes when the properties are accessed and modified. Each component instance has a corresponding watcher program instance, which records the properties as dependencies during component rendering. Later, when the dependency's setter is called, the watcher will be notified to recalculate, causing its associated components to be updated. .

Source code: How to optimize reordering and redrawing in vue

Vue optimizes reflow and redrawing by using virtual DOM (virtual DOM). Virtual DOM is a technology that compares old and new DOM trees to determine which changes need to be applied to the actual DOM. When DOM elements change, Vue automatically detects and re-renders the DOM without affecting performance, making redrawing and reflowing more efficient.

Vue modifies the view through data binding. When a certain data is modified, the set method will cause the Dep in the closure to call notify to notify all subscribers Watcher. The Watcher executes vm._update(...) through the get method, and then updates. view.

In vm._update(...), Vue will call patch(...) to compare the newly generated vnode with the old prevVnode before the data has not changed.

In the patch(...) method, Vue uses sameVnode(...) to compare the old and new Vnode objects by comparing their tag names (tag), key values ​​(key), and whether they both have the data option (isDef(data) ) and whether they are both comment nodes (isComment) to determine that the real DOM nodes mapped by these two Vnodes are the same. Only when it is determined that they are different mappings of the same real DOM node will the next step of patchVnode(...) be executed.

In patchVnode(…), Vue will perform different DOM operations based on whether the old and new Vnode objects have child nodes. When both Vnode objects have child nodes, the updateChildren(…) method will be called to recursively perform operations on the child nodes. patchVnode(…).

The implementation of v-model and its implementation principle?

  1. Two-way binding in Vue is an instruction v-model, which can bind a dynamic value to the view, and changes in the view can change the value. v-model is syntactic sugar, equivalent to :value and @input by default.

  2. Using v-model can reduce a lot of tedious event processing code, improve development efficiency, and make the code more readable.

  3. Typically v-model is used on form items

  4. Native form items can use v-model directly. If you want to use it on a custom component, you need to bind the value within the component and handle the input event.

  5. I did a test and output the component rendering function containing the v-model template, and found that it will be converted into a binding of the value attribute and an event listener, and the corresponding variable update operation will be performed in the event callback function, which shows that the magic is actually Completed by vue's compiler.

The entire process after new Vue

initProxy: Scope proxy, intercepts data accessed from other components within the component.
initLifecycle: Establish a parent-child component relationship, and add some attributes and life cycle identifiers to the current component instance. Such as [Math Processing Error]parent, parent, refs, $children, _isMounted, etc.
initEvents: Add a listener to the event passed in by the parent component. Whoever created the event listens to it. Subcomponent creation event subcomponent listens
initRender: declares [Math Processing Error] slots and slots and createElement(), etc.
initInjections: Inject data, initialize inject, generally used for deeper communication between components.
initState: important) data responsive: initialization state. Summary of many options for initialization: data, methods, props, computed and watch.
initProvide: Provides data injection.
Thinking: Why inject first and then provide? ?

1. First, the data from the ancestors must be combined with the data of the current instance, so the initInjections of the injected data must be above the InitState.

  1. Things injected from above are transferred in the current component and provided to future generations, so the injected data must also be above.

Implementation of keep-alive

Role: Implement component caching

Hook function:
activated called after the component is rendered

deactivated Called after component is destroyed

Principle: Vue.js internally abstracts DOM nodes into VNode nodes. The cache of the keep-alive component is also based on VNode nodes instead of directly storing the DOM structure. It caches the components that meet the conditions (pruneCache and pruneCache) in the cache object, and then takes the vnode node out of the cache object and renders it when it needs to be re-rendered.

Configuration properties:
include string or regular expression. Only components with matching names will be cached

exclude string or regular expression. Any component with a matching name will not be cached

max number, the maximum number of component instances that can be cached

Implementation principles of vuex and vue-router

vuex is a state management library developed specifically for vue.js applications. Core idea:

state (single state tree) getter/Mutation display commit change state
Action is similar to Mutation, commit Mutation, can include any asynchronous operation.
module (when the application becomes large and complex, split the store into specific module modules)
How do you understand the diff algorithm in Vue?
In js, the cost of rendering the real DOM is very high. For example, if we modify a certain data, if Rendering directly to the real DOM will cause the entire DOM tree to be redrawn and rearranged. So is it possible to update only the small piece of DOM we modified instead of updating the entire DOM? At this time, we need to first generate a virtual dom based on the real dom. When the data of a certain node of the virtual dom changes, a new Vnode will be generated. Then compare the new Vnode with the old Vnode. If there is any difference, directly Modify the real DOM, and then make the value of the old Vnode the new Vnode.

The process of diff is to call the patch function, compare the old and new nodes, and patch the real DOM while comparing. When using the diff algorithm to compare old and new nodes, the comparison will only be performed at the same level. In the patch method, tree-level comparison is first performed. If the new Vnode does not exist, delete the old Vnode. If the old Vnode does not exist, add a new Vnode. If both exist, perform a diff update. When it is determined that the diff algorithm needs to be executed, compare the two Vnodes, including three types. Operation: attribute update, text update, child node update. Both the old and new nodes have child nodes, then perform a diff operation on the child nodes and call updatechidren. If the old node has no child nodes and the new node has child nodes, clear the text content of the old node first. Then add a new child node to it. If the new node has no child nodes and the old node has child nodes, remove all the child nodes of the node. When the old and new nodes have no child nodes, replace the text.

updateChildren extracts the child node Vch of Vnode and the child node oldCh of oldVnode. oldCh and vCh each have two head and tail variables StartIdx and EndIdx. Their two variables are compared with each other. There are a total of 4 comparison methods. If none of the four comparisons match, if the key is set, the key will be used for comparison. During the comparison process, the variable will move to the middle. Once StartIdx>EndIdx indicates that at least one of oldCh and vCh has been traversed, it will end. Compare.

What happens when the browser enters the URL and renders the page?

three aspects:

Network:

  1. Build request

  2. Find strong cache

  3. DNS resolution

  4. Establish TCP connection (three-way handshake)

  5. Send HTTP request (network response after network request)

Browser analysis:

  1. Parse html to build DOM tree

  2. Parse css to build CSS tree and style calculation

  3. Generate layout tree (Layout Tree)

Browser rendering:

  1. Create layer tree (Layer Tree)

  2. Generate draw list

  3. Generate tiles and rasterize

  4. Display content

  5. Final disconnect: TCP four waves

The difference between HTTP and HTTPS (high frequency)

1. HTTPIt is insecure, while HTTPS is secure

2. HTTPThe standard port is 80, while the standard port of HTTPS is 443

3. HTTPUnable to encrypt, while HTTPS encrypts transmitted data

4. HTTPNo certificate is required, while HTTPS requires an SSL certificate from a CA

The difference between GET and POST (high frequency)

1. GET will not request again when the browser returns, and POST will submit the request again.

2. GET requests will be actively cached by the browser, but POST requests will not and must be set manually.

3. The GET request parameters will be completely retained in the browser history, but the parameters in POST will not

4. There is a length limit on the parameters transmitted in the URL for the GET request, but there is no limit for POST.

5.GET parameters are passed through the URL, and POST is placed in the Request body.

6. It is not safe for GET parameters to be exposed in the address bar, but it is safer to put POST parameters inside the message.

7.GET is generally used to query information, and POST is generally used to submit certain information for certain modification operations.

8.GET generates one TCP data packet; POST generates two TCP data packets

Understand the principles of xss, csrf, ddos ​​attacks and how to avoid them

XSS (Cross-Site Scripting, cross-site scripting attack) is a code injection attack. The attacker injects malicious code into the target website. When the attacker logs in to the website, the malicious code will be executed. These scripts can read cookies, session tokens, or other sensitive website information, conduct phishing and fraud on users, and even launch worms. Attack etc.

CSRF (Cross-site request forgery) Cross-site request forgery: The attacker induces the victim to enter a third-party website, and in the third-party website, sends a cross-site request to the attacked website. Using the registration credentials that the victim has obtained on the attacked website, bypassing the background user verification, the purpose of impersonating the user is to perform an operation on the attacked website.

XSS avoidance methods:

  1. The url parameters are escaped using the encodeURIComponent method

  2. Try not to have InnerHtml insert HTML content

  3. Use special symbols, label escapes.

How to avoid CSRF:

  1. Add verification code

  2. Use token

The server generates a token for the user, encrypts it and passes it to the user.

Users need to carry this token when submitting a request

The server verifies whether the token is correct

http characteristics and status codes

for example:

200响应成功

301永久重定向

302临时重定向

304资源缓存

403服务器禁止访问

404服务器资源未找到

500 502服务器内部错误

504 服务器繁忙

1xx Informational(信息状态码)   接受请求正在处理

2xx Success(成功状态码)            请求正常处理完毕

3xx Redirection(重定向状态码)  需要附加操作已完成请求

4xx Client Error(客户端错误状态码) 服务器无法处理请求

5xx Server Error(服务器错误状态码) 服务器处理请求出错复制代码

How to implement caching in http

  1. Strong cache ==> Expires (expiration time)/Cache-Control (no-cache) (high priority) Negotiation cache ==> Last-Modified/Etag (high priority) Etag is suitable for small files that change frequently Last-Modefied Suitable for large files that change infrequently

  2. Both the strong cache strategy and the negotiation cache strategy will directly use the local cache copy when the cache is hit. The only difference is that the negotiation cache will send a request to the server. When their cache misses, they will send requests to the server to obtain resources. In the actual caching mechanism, the strong caching strategy and the negotiated caching strategy are used together. The browser will first determine whether the strong cache hits based on the requested information. If it hits, the resource will be used directly. If there is a miss, a request is made to the server based on the header information, using the negotiated cache. If the negotiated cache hits, the server does not return the resource, and the browser directly uses a copy of the local resource. If the negotiated cache fails, the browser returns the latest resource. to the browser.

What is the same origin policy

JS scripts in one domain cannot access content in another domain without permission. Usually, the basis for judging cross-domain is whether the protocol, domain name, and port number are the same. If they are different, it means cross-domain. The same-origin policy is a restriction on js scripts, not a restriction on browsers. For example, img and script requests will not have cross-domain restrictions.

How the front and back ends communicate

Ajax: short connection

Websocket: Long connection, two-way.

Form form: the most original

Several ways of cross-domain communication

solution:

  1. jsonp (implemented by exploiting the vulnerability of script tags without cross-domain restrictions. Disadvantages: only supports GET requests)

  2. CORS (set Access-Control-Allow-Origin: specify the domain name of accessible resources)

  3. postMessage(message, targetOrigin, [transfer]) (HTML5 new API for multi-window messages and page embedded iframe messaging), monitor the passed data through onmessage

  4. Websocket is a persistent protocol of HTML5. It realizes full-duplex communication between the browser and the server and is also a cross-domain solution.

  5. Node middleware proxy

  6. Nginx reverse proxy

  7. Various ways of nesting iframes are not commonly used.

  8. The most suitable cross-domain solutions used in daily work are CORS and Nginx reverse proxy

Front-end engineering

Webpack configuration, what are the optimization points of webpack4.0

module.exports={

entry: {},

output: {},

plugins: [],

module: [rules:[{}]]

}

How webpack implements code separation

1. Entry starting point: Use entry configuration to manually separate the code.

2. Prevent duplication: Use CommonsChunkPlugin to remove duplicates and separate chunks.

3.Dynamic imports: Separate code through inline function calls of modules.

Common Webpack Loader? How to implement a Webpack Loader(NO)

loader: It is a javascript module exported as a function, which matches the file extension according to the rules and processes the converter of the file.

file-loader: Output the file to a folder, and reference the output file through a relative URL in the code (processing images and fonts)

url-loader: Similar to file-loader, the difference is that the user can set a threshold. If it is greater than the threshold, it will be handed over to file-loader for processing. If it is less than the threshold, it will return the file base64 format encoding (processing pictures and fonts)

image-loader: Load and compress image files

babel-loader: Convert ES6 to ES5

sass-loader: Convert SCSS/SASS code to CSS

css-loader: loads CSS, supports modularization, compression, file import and other features

style-loader: Inject CSS code into JavaScript and load CSS through DOM operations

postcss-loader: Extends CSS syntax, uses next-generation CSS, and can automatically complete CSS3 prefixes with the autoprefixer plug-in. eslint-loader: Checks JavaScript code through ESLint

Common Webpack Plugin? How to implement a Webpack Plugin (NO)
plugin: Essentially a plug-in, based on the event flow framework Tapable, the plug-in can extend the functions of Webpack. Many events will be broadcast during the life cycle of Webpack running, and the Plugin can monitor these events. , change the output results at the appropriate time through the API provided by Webpack.

html-webpack-plugin: Simplify HTML file creation (depends on html-loader)

uglifyjs-webpack-plugin: compress js files

clean-webpack-plugin: Directory cleaning

mini-css-extract-plugin: separate style files, extract CSS into independent files, support on-demand loading (replaces extract-text-webpack-plugin)

Compare loader and plugin?
Loader is configured in module.rules as the parsing rule of the module, and its type is an array. Each item is an Object, which contains attributes such as test (type file), loader, options (parameters), etc.
Plugin is configured separately in plugins, and its type is an array. Each item is an instance of Plugin, and the parameters are passed in through the constructor.

Front-end modularization, CMD, AMD, CommonJS

CommonJS

CommonJS is a specification for server-side modules, popularized and used by Node, and webpack is also written using this specification.

commonJs specification:
CommonJS module specification is mainly divided into three parts: module definition, module identification, and module reference.

Module definition: module object: In each module, the module object represents the module itself. export attribute: an attribute of the module object, which provides an interface to the outside world. The best way to export module variables is to use the module.exports object. A single file is a module. Each module has a separate scope, that is to say, variables defined within the module cannot be read by other modules unless they are defined as attributes of the global object.

Module identification: The parameters passed to the require method must be a string named in camel case, or a relative path starting with ., ..., or an absolute path.

Module reference: Load modules using require (synchronous loading). This method reads a file and executes it, returning the module.exports object inside the file.

Advantages:
On the backend, the JavaScript specification is far behind and has many flaws, which makes it difficult to develop large-scale applications using JavaScript. For example: no module system, few standard libraries, no standard interfaces, lack of package management system, list content

CommonJS module specifications solve the problem of variable pollution very well. Each module has an independent space and does not interfere with each other. Namespaces are not very good in comparison.

The CommonJS specification definition module is very simple and the interface is very concise.

CommonJS module specification supports import and export functions, so that each module can be smoothly connected and dependencies between each other can be realized

The CommonJS specification was proposed mainly to make up for the lack of standards in JavaScript, and to have the basic capabilities to develop large-scale applications like Python, Ruby and Java, instead of staying at the stage of developing small browser-side scripts.

Disadvantages:
No parallel loading mechanism

Since CommonJS loads modules synchronously, this is very bad for the server side because all modules are placed on the local hard disk. The waiting time for the module is the time it takes for the hard disk to read files, which is very small. However, for the browser, it needs to load the module from the server, which involves network speed, proxy and other reasons. Once the waiting time is too long, the browser will be in a "suspended death" state.

Therefore, the browser side is not very suitable for Common.Js, and another standard AMD has emerged.

AMD

AMD is an asynchronous module definition specification that runs in the browser environment. It is the standardized output of module definitions during the promotion process of RequireJS.

AMD specifications
AMD recommends pre-dependency. When defining a module, you must declare the modules it depends on.

Advantages
: The user experience is good because there is no delay and dependent modules are executed in advance.
CMD
CMD is a general module definition specification; it is the standardized output of module definition in the promotion process of SeaJs

CMD specification
CMD recommends dependencies that are nearby and will only require when a certain module is used.

Advantages
: Good performance because it is only executed when the user needs it.

Anti-shake throttling

Function anti-shake focuses on continuous triggering for a certain period of time and only executes once at the end, while function throttling focuses on executing only once within a period of time.

Anti-shake

//Definition: The function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated. //Search input in the search box. As long as the user completes the last input, the request is sent //Mobile phone number, email verification input detection onchange oninput event //Window size Resize. Simply calculate the window size after the window resize is complete. Prevent re-rendering.

 const debounce = (fn, wait, immediate) => { let timer = null;  return function (...args) {  if (timer) clearTimeout(timer);   if (immediate && !timer) {      fn.call(this, args);   } timer = setTimeout(() => {   fn.call(this, args); }, wait); }; };const betterFn = debounce(() => console.log("fn 防抖执行了"), 1000, true);document.addEventListener("scroll", betterFn);

Throttle

//Definition: When an event is continuously triggered, the event is guaranteed to be triggered once every interval. //1. Lazy loading, rolling loading, loading more or monitoring the scroll bar position; //2. Baidu search box, search association function; //3. Prevent high-frequency click submission and prevent repeated submission of forms.

function throttle(fn,wait){
    let pre = 0;
 
    return function(...args){
 
        let now = Date.now();
 
        if( now - pre >= wait){
 
            fn.apply(this,args);
 
            pre = now;
 
        }
 
    }
 
}function handle(){
 
    console.log(Math.random());
 
}window.addEventListener("mousemove",throttle(handle,1000));

Deep and shallow copies of objects

//浅拷贝 1. Object.assign(target,source)2. es6对象扩展运算符。//深拷贝    function deepClone(obj) {
      if (!obj || typeof obj !== "object") return;
      let newObj = Array.isArray(obj) ? [] : {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key];
        }
      }
      return newObj;
}

Array deduplication, array object deduplication

//数组
 
const arr = [2,7,5,7,2,8,9];
 
console.log([...new Set(arr)]);// [2,7,5,8,9];
 
//对象
 
const list = [{age:18,name:'张三'},{age:18,name:'李四'},{age:18,name:'王五'}]
 
let hash = {};
 
const newArr = arr.reduce((item, next) => {
 
    hash[next.age] ? '' : hash[next.age] = true && item.push(next);
 
    return item;
 
}, []);console.log(list);

Array flattening

function flatten(arr) {
 
      return arr.reduce((result, item) => {
 
        return result.concat(Array.isArray(item) ? flatten(item) : item);
 
      }, []);
 
}

Performance optimization

What performance optimizations have you done on Vue?

Mobile performance optimization:

  1. Keep individual files less than 25KB:
    Mobile website pages require downloading resources. If the file is too large, it will greatly slow down the page loading speed.

  2. The packaged content is a segmented multipart document:
    Since each HTTP request will perform a three-way handshake, each handshake will consume more time. Using multipart, multiple files can be uploaded at the same time, and multiple components can be obtained with one HTTP request.

Image optimization:

  1. CSS sprites:
    commonly known as CSS sprites, sprite pictures, snowflake pictures, etc. It is a solution to merge multiple small pictures into one picture to reduce HTTP requests. Image content can be accessed through the background property in CSS. This solution can also reduce the total number of bytes of the image and save naming vocabulary.

  2. Compress images:
    Images take up a lot of resources, so try to avoid using redundant images. When using them, choose the most appropriate format size, then use Smart Image compression, and use Srcset in the code to display on demand. (Remember not to over-compress as it may cause blurry images)

  3. Try to avoid resizing the image:
    Resizing the image refers to resizing the image multiple times in the page, CSS, JavaScript, etc. Resizing the image multiple times will cause the image to be redrawn multiple times, affecting performance.

  4. Try to avoid using DataURL for images:
    If DataURL images do not use the image compression algorithm, the file will become larger and must be decoded before rendering, which makes loading slow and time-consuming.

  5. Lazy loading of images:
    Images have a great impact on page loading speed. For example, when a page contains a lot of content, the loading speed will be greatly reduced, which will greatly affect the user experience. What's more, a page may have hundreds of images, but only the first few images are displayed on the page. Can other images be loaded later to improve performance? See details >>

JavaScript related optimization

  1. Place the script at the bottom of the page:
    placing it at the front will cause blocking of js loading and affect the loading of dom later.

  2. Using external JavaScript and CSS:
    Using external files in a real-world environment will usually produce faster pages because JavaScript and CSS have a chance to be cached by the browser. In the inline case, since HTML documents are typically not configured to be cacheable, JavaScript and CSS are downloaded each time the HTML document is requested. So, if the JavaScript and CSS are in external files, the browser can cache them and the size of the HTML document will be reduced without increasing the number of HTTP requests.

  3. Compress JavaScript and CSS:
    Compressing files is to reduce network transmission volume and reduce the response time of page requests.

  4. Reduce DOM operations:
    Operating DOM will produce several actions, which greatly affects the rendering efficiency. Among them, layout (layout) and paint (drawing) are the largest.

  5. JS overhead shortens the parsing time:
    Overhead: Loading -> Parsing and compilation -> Executing
    js parsing and compilation, the execution takes a long time (you can view it in the performance of Google development tools. Select a certain section in the main thread.)
    solution:

    • Code splitting for on-demand loading
    • tree shaking code weight reduction
    • Avoid long tasks
    • requestAnimationFrame and repeatIdleCallback perform time scheduling
  6. v8 compilation principle (code optimization):

    • Parse js code into abstract syntax tree -"bytecode-"machine code. The
      compilation process will be optimized,
      and de-optimization may occur during runtime.
    • V8 internal optimization
      script flow: parsing while downloading
      bytecode cache: commonly used bytecodes will be stored (this file uses parameters that are also used by other files)
      function lazy parsing: parse the used ones first
    • Object optimization (optimization catering to v8)
      ensures that the object initialization sequence is consistent (v8 will generate hidden attributes for subsequent reuse when the object is initialized and sorted in order). Do not directly
      assign new attributes of the object (additional attributes need to be indirectly searched through the description array)
      Use an array instead of a class array (v8 will optimize the array). For example, convert the class array into an array first
      to avoid reading the array out of bounds (for example, if the for loop searches for one more subscript, the performance will be 6 times worse)

Causes undefined and numerical comparison.
Arrays are also objects. When the corresponding subscript cannot be found, it will be searched up along the prototype chain, causing additional overhead. It is invalid
in business.

  1. js memory to avoid memory leaks:
    determine whether the memory is released by whether the variable can be accessed.
  • Local variables: After the function is executed and there is no closure reference, it will be marked for recycling.
  • Global variables: until the browser is unloaded and the page is released
  • Recycling mechanism:
    Reference count: increase by one each time it is called, and recycle when the count reaches 0. The disadvantage is that it cannot resolve circular references (for example, object a depends on object b, mark and clear (garbage collection): access from the root node, when an object that cannot be accessed is accessed, mark it and then perform garbage collection. (When object a is resolved
    : Avoid unexpected global variables; avoid closures caused by repeated runs; avoid detached DOM elements from not being recycled (so react has the ref API).

CSS related optimization

  1. Put the style sheet in the tag:
    Putting the css in the head tag requires one less time to build the RenderTree, one time to calculate the layout and one time to render the web page than putting the css at the end of the body tag, so the performance will be better.
  2. Don't use CSS stylesheets
  3. Use an alternative to @import
  4. Don't use filter
  5. Avoid element type conversion (putting multiple types in the array is not conducive to v8 engine optimization code)
    • Reduce css blocking on rendering (load on demand, load in front of dom)
    • Use pu to complete animation (composite mentioned earlier)
    • Use contain for optimization (optimization is strong. For example: contan:layout tells the browser that the child elements inside this node and the outside ones are optimized using font-display: let the text be displayed on the page earlier and reduce the problem of text flashing

html related optimization

  1. Reduce iframe usage
  2. compress whitespace
  3. Avoid nesting levels too deep
  4. Avoid using table layout
  5. Reduce unnecessary comments
  6. Delete element default attributes (such as default checkbox, etc.)

Develop content-related optimization

  1. Reduce the number of HTTP requests
  2. Reduce DNS redirects
  3. Caching AJax requests
  4. Lazy loading
  5. Preloading
  6. Reduce the number of DOM elements
  7. Divide content into different domain names
  8. Minimize use of iframes
  9. Avoid 404 errors

Server related optimization

  1. Use CDN
  2. Add Expires or Cache-Control response header
  3. Enable Gzip
  4. Configure Etag
  5. Early output buffering
  6. Ajax request using GET method
  7. Avoid empty image src
  8. Transport loading optimization
    Server enabled gzip
  9. keep Alive (persistent TCP connection)
    keepalive_requests 100; keepAlive that opens http after 100 requests has keepalive_timeout 65; closes after 65 seconds.
  10. It is best to use no-cache for http
    cache (you need to verify it with Etag on the server side when you want to use it)
  11. service workers
    • Speed ​​up repeat visits
    • Offline support

Cookie related optimization

  1. Reduce cookie size
  2. Static resources use cookie-less domain names

First screen loading optimization

  1. Resource compression, transmission compression, code splitting, tree shaking, http caching
  2. Route lazy loading, pre-rendering, inlineCss, virtual list
  3. prefetch and preload adjust loading order js memory management

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/129258564