Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Nonsense only say 1: code word is not easy to seek a 👍, collect === learn, quick action! 🙇 🙇 🙇.


1. The HTTP and HTTPS

1. Basic concepts of HTTP and HTTPS

HTTP: a client – and server-side request and response standard (TCP) hypertext transfer protocol for transferring hypertext from WWW servers to local browsers. HTTPS: the HTTP channel aims at security. That is, the SSL layer is added to the HTTP layer for encryption. Its function is: establish an information security channel, to ensure the transmission of data, to ensure the authenticity of the website.

2. What are the differences, advantages and disadvantages between HTTP and HTTPS?

  • HTTP is a hypertext transfer protocol. Information is transmitted in plain text. HTTPS is better than HTTPsecurityHTTPS is a secure SSL encryption transmission protocol, preventing data from being stolen or changed during transmission and ensuring data integrity.
  • The HTTP protocolThe default portIs 80. The default HTTPS port is 443.
  • HTTP connections are simple and stateless. HTTPS handshake phase comparisonTime consuming, the page loading time is prolonged by 50% and the power consumption is increased by 10%~20%.
  • https The cacheIt is not as efficient as HTTP and increases data overhead.
  • Https requires a CA certificate, which costs more and has more powerful functionsCertificate feeWith the higher.
  • The SSL certificate needs to be boundIPYou cannot bind multiple domain names to the same IP address. IPV4 resources cannot support such consumption.

3. The working principle of HTTPS

When a client uses HTTPS to communicate with the Web server, perform the following steps:

  1. If the client accesses the server using the HTTPS URL, the web server is requiredEstablishing SSL links.
  2. When the Web server receives the request from the client, theTransfer the web site's certificate, which contains the public key, to the client.
  3. Start on the client and Web server sidesNegotiates the security level of SSL links, which is the encryption level.
  4. The client browser passes the security level agreed by both parties.Establishing a session key, then encrypts the session key through the site’s public key and sends it to the site.
  5. The web serverDecrypt the session key using its own private key.
  6. The web serverThe communication between the client and the session key is encrypted.

☞ Interpret HTTP1/HTTP2/HTTP3

TCP three-way handshake

  1. First handshake:When establishing a connection, the client sends a SYN packet (SYN = J) to the server and enters the SYN_SENT state, waiting for the server to confirm; SYN: Indicates the Synchronize Sequence number.
  2. Second handshake:The server receives a SYN packet and acknowledges the client's SYN(ack = j + 1),It also sends its own SYN packet(SYN = K), that is, SYN+ACK packets. The server enters the SYN_RECV state.
  3. Third handshake:The client receives a SYN+ACK packet from the server and sends an ACK(ACK = K +1) to the server.After the packet is sent, the client and server enter the ESTABLISHED state (TCP connection is successful) and complete the three-way handshake.

The packet transmitted during the handshake does not contain data. After three handshakes, the client and server start data transmission.

TCP waved four times

  1. The client process sends a connection release packetAnd stop sending data. Release the header of the data packet, FIN=1, whose serial number is seq=u (equal to the serial number of the last byte of the previously transmitted data plus 1).The client enters the fin-WaIT-1 state. According to TCP, FIN packets consume a sequence number even if they do not carry data.

2) After receiving the connection release packet, the server sends an acknowledgement packet with ACK=1, ACK= U +1 and its serial number seq= V. Then, the server enters the close-wait state. The TCP server notifies the higher-level application process that the client is released from the direction of the server. This state is half-closed, that is, the client has no data to send, but if the server sends data, the client still accepts it. This state also lasts for a period of time, i.e. the duration of the close-wait state.

3) After receiving the acknowledgement request from the server, the client enters the fin-WaIT-2 state and waits for the server to send the connection release message (before receiving the last data sent by the server).

4) After sending the final data, the server sends a connection release packet to the client, FIN=1, ACK = U +1. Because the server is in the semi-closed state, it is likely to send some more data. Assume that the serial number is SEQ = W, then the server enters the last-ACK state, waiting for the confirmation of the client.

5) After receiving the connection release packet from the server, the client must send an acknowledgement with ACK=1, ACK= W +1 and its serial number is SEq = U +1. In this case, the client enters the time-wait state. Notice That the TCP connection is not released at this time, and the client can enter the CLOSED state only after 2∗∗MSL (maximum packet segment life) and the corresponding TCB is revoked.

6) As long as the server receives the confirmation from the client, it will enter the CLOSED state immediately. Similarly, revoking the TCB terminates the TCP connection. As you can see, the server ends the TCP connection earlier than the client.

How can TCP/IP/ensure the orderly and reliable transmission of data packets?

Byte streams are segmented and numbered and then guaranteed by ACK replies and timeout retransmissions.

(1) In order to ensure reliable transmission of data packets, the sender must keep the sent data packets in the buffer; (2) Start a timeout timer for each sent packet; (3) If a reply message is received before the timer times out, the buffer occupied by the packet is released. (4) Otherwise, the packet is retransmitted until the response is received or the retransmission times exceed the specified maximum times. (5) After receiving the packet, the receiver will perform CRC check first. If it is correct, the data will be handed over to the upper layer protocol, and then send a cumulative reply packet to the sender, indicating that the data has been received. If the receiver just has data to send to the sender, the reply packet can also be carried in the packet.

Differences between TCP and UDP

  1. TCP is forlinkUDP is connectionless.
  2. TCP is only supportedUnicast transmissionUDP provides unicast, multicast and broadcast functions.
  3. TCP’s three-way handshake guarantees a connectionreliability; UDP is a connectionless and unreliable data transmission protocol. It is unreliable because no connection is required for communication and no confirmation signal is sent for received data. The sender does not know whether the data can be correctly received.
  4. The UDPThe head of overheadSmaller than TCP, dataHigher transmission rate.Better real-time.

☞ In-depth analysis of the differences between TCP and UDP

HTTP request cross domain problems

  1. Cross-domain principles

    Cross-domain means that the browser cannot execute scripts from other sites. It is caused by the same origin policy of the browser. The same origin policy is a security restriction imposed by browsers on JavaScript. Any difference in protocol, domain name, or port is considered as a different domain. The cross-domain principle is to circumvent browser security restrictions in various ways.

  2. The solution

    In the initial project, JSONP was used, but there were some problems, such as insecure use of GET request and small data carried. Later, IFrame was also used, but only the primary domain was the same, and there were also some problems. Later, through understanding and learning, I found that it was convenient to use proxy and proxy together. Guide the background according to this way to do the server configuration, in the development of proxy, the use of nginx proxy on the server, so that the development process is convenient to each other, high efficiency; Windows.postmessage () is now available in H5.

    • Json: Ajax requests are not allowed to make cross-domain requests due to the same origin policy, whereas the link in the SRC attribute of the script tag can access cross-domain JS scripts. With this feature, the server no longer returns JSON data, but returns a piece of JAVASCRIPT code that calls a function. The call is made in SRC, which is cross-domain.

      Steps:

      1. To create a script tag
      2. The SRC property of script sets the interface address
      3. Interface parameter, must have a custom function name, otherwise background cannot return data
      4. Accept the returned data by defining the function name
      // Create script dynamically
      var script = document.createElement('script');
      
      // Set the callback function
      function getData(data) {
          console.log(data);
      }
      
      // Set the SRC property of the script and set the request address
      script.src = 'http://localhost:3000/? callback=getData';
      
      // make script work
      document.body.appendChild(script);
      Copy the code

      Disadvantages of JSONP: JSON only supports GET, because script tags can only use GET requests; JSONP requires backend coordination to return data in the specified format.

    • Document. domain The base domain name is the same as the subdomain name

    • Window. name uses a browser window to load all domain names that share a window.name

    • CORS Cross-origin Resource Sharing (CORS) Server Settings The principles of CORS are as follows: After the access-Control-allow-Origin HTTP response header is set on the server, the browser allows cross-domain requests

    • Proxy Proxy is used to set the proxy on the server

    • Window.postmessage () takes advantage of the new H5 feature window.postmessage ()

Cookie, sessionStorage, localStorage

Similarities:

  • Stored on the client

Difference:

  • Cookie data size cannot exceed 4K; SessionStorage and localStorage store much larger than cookies, up to 5M+
  • The cookie is valid until the expiration time; LocalStorage permanent storage, browser closed data will not be lost unless actively delete data; SessionStorage data is automatically deleted after the current browser window is closed
  • Cookie data will be automatically transferred to the server; SessionStorage and localStorage data are stored locally

Analysis and countermeasures of sticky bag problem

TCP sticky packets refer to packets sent by the sender and received by the receiver. From the view of the receiving buffer, the first packet is followed by the last packet.

Cause of sticky package

Simply put, UDP does not appear sticky packets in stream traffic because it has message boundaries

There are two types of sticky packets. One is that the stuck packets are complete packets, and the other is that the stuck packets are incomplete packets.

To avoid sticky bags, you can take the following measures:

(1) For the sticky packet phenomenon caused by the sender, the user can avoid it through programming Settings. TCP provides the operation instruction push that forces the data to be transmitted immediately. After receiving the operation instruction, TCP software immediately sends out this section of data without waiting for the sending buffer to be full.

(2) For sticky packets caused by the receiver, it can optimize the program design, simplify the workload of the receiving process, improve the priority of the receiving process and other measures to make it receive data in time, so as to avoid sticky packets as much as possible;

(3) Controlled by the receiver, a packet of data according to the structure field, artificial control divided into multiple reception, and then merged, through this means to avoid sticky packets. Frequent subcontracting.

All three measures mentioned above have their shortcomings.

(1) Although the first programming setting method can avoid sticky packets caused by the sender, it turns off the optimization algorithm, reduces the network transmission efficiency, affects the performance of the application, and is generally not recommended.

(2) The second method can only reduce the possibility of sticky packets, but cannot completely avoid sticky packets. When the transmission frequency is high, or the network burst may make the packet arrive at the receiver faster in a certain period, the receiver may still fail to receive the packet, resulting in sticky packets.

(3) Although the third method avoids sticky packages, the application efficiency is low and it is not suitable for real-time applications.

A more comprehensive solution is that the receiver creates a preprocessing thread to preprocess the received packets and separate the sticky packets. Experiments show that this method is efficient and feasible.

The browser

The entire process from entering the URL to loading the page

  1. Start by entering the URL in your browser

  2. Search cache: The browser first checks whether the address page exists in the browser caches, system caches, and route caches. If so, the page content is displayed. If not, proceed to the next step.

    • Browser cache: The browser keeps DNS records for some time, so it is only the first place to resolve DNS requests;
    • Operating system cache: If this record is not included in the browser cache, the system will call the operating system to get the operating system record (saving the recent DNS query cache).
    • Router cache: If the preceding two steps fail to obtain DNS records, continue to search the router cache.
    • ISP cache: If all the preceding parameters fail, continue to search for the ISP.
  3. DNS domain name resolution: The browser sends a request to the DNS server to resolve the IP address corresponding to the domain name in the URL. The DNS server is based on UDP, and therefore uses UDP.

  4. Establish A TCP connection: After the IP address is resolved, establish a TCP connection with the server based on the IP address and port 80 by default

  5. Initiating an HTTP request: The browser initiates an HTTP request to read a file. The request packet is sent to the server as the third data of the TCP three-way handshake

  6. The server responds to the request and returns the result: The server responds to the browser request and sends the corresponding HTML file to the browser

  7. Close THE TCP connection: Release the TCP connection with four waves

  8. Browser rendering: The client (browser) parses the HTML content and renders it. After the browser receives the data packet, the parsing process is as follows:

    • Build A DOM tree: lexical analysis and then parse into a DOM tree (DOM tree), is composed of DOM elements and attribute nodes, the root of the tree is the Document object
    • Building a CSS Rule Tree: Generating a CSS Rule Tree
    • Build a Render tree: Web browsers combine DOM and CSSOM to build a render tree
    • Layout: Calculates the position of each node on the screen
    • Painting: Traverse the Render tree and paint each node using the UI back-end layer.

  9. JS engine parsing process: Call JS engine to execute JS code (JS interpretation stage, preprocessing stage, execution stage to generate execution context, VO, scope chain, recycle mechanism, etc.)

    • Create the Window object: The Window object is also called the global execution environment. It is created when the page is created. All global variables and functions belong to the properties and methods of the window, and the DOM Tree maps to the Doucment object of the window. The global execution environment is destroyed when the web page or browser is closed.
    • Loading file: complete JS engine analysis of its syntax and morphology is legal, if legal into precompilation
    • Precompilation: During precompilation, the browser looks for the global variable declaration, adds it to the window object as a property of window, and assigns the variable ‘undefined’; Look for the global function declaration, add it to the window object as a method of window, and assign the function body to it (anonymous functions are not precompiled because they are variables). While variable promotion as an unreasonable area has been resolved in ES6, function promotion still exists.
    • If the variable is not defined, it is not precompiled. In ES5 non-strict mode, the variable becomes an attribute of the window, i.e. a global variable. Values such as string and int are put directly into the storage space of variables, and objects are Pointers to the storage space of variables. When the function is executed, it pushes the function’s environment onto the stack of an environment, and pops up again after execution, handing control back to the previous environment. JS scope is implemented by such an execution flow mechanism.

What is the difference between browser redraw and rearrangement?

  • Rearrangement/Reflow: whenDOMThe browser needs to recalculate the element’s geometry to place it in the correct position on the interface, a process called rearrangement. This takes the form of regenerating the layout and rearranging elements.
  • Redraw (Repaint)The process of redrawing an element when its appearance is changed without changing its layout is called redrawing. The appearance of some elements is changed

Changing the appearance of the elements alone will certainly not cause the layout of the page to be redrawn, but when the browser completes the rearrangement, it will redraw the parts affected by the rearrangement

Rearrange and redraw are expensive, they can ruin the user experience and make the UI display very slow, while rearrange has a greater performance impact, and when both are unavoidable, we generally prefer the cheaper redraw.

“Redraw” does not necessarily lead to “rearrange”, “rearrange” necessarily leads to “redraw”.

How to trigger rearrangement and redraw?

Any changes to the information used to build the render tree will result in a rearrangement or redraw:

  • Add, delete, and update DOM nodes
  • Hide a DOM node with display: None – triggering rearrangement and redrawing
  • Hide a DOM node by visibility: Hidden – only triggers redraw because there are no geometric changes
  • Move or animate the DOM nodes in the page
  • Add a style sheet and adjust the style properties
  • User actions, such as resizing a window, changing font size, or scrolling.

How to avoid redrawing or rearranging?

  1. Focus on styling, rather than changing the STYLE of the DOM line by line.

  2. Do not place DOM node property values in the loop as variables in the loop.

  3. Use fixed or Absoult position for animated HTML elements, then modifying their CSS will not reflow.

  4. Do not use the table layout. Because a small change can cause the entire table to be rearranged.

  5. Try to change only the position: absolute or fixed element, with little effect on other elements

  6. Animation starts with GPU acceleration, Translate uses 3D changes

  7. Ascend to the synthesis layer

    Promoting elements to the composition layer has the following advantages:

    • The bitmap of the composite layer will be synthesized by the GPU faster than the CPU
    • When repaint is required, only repaint itself is required and no other layers are affected
    • Layout and Paint are not triggered for Transform and opacity effects

    The best way to improve the composition layer is to use the will-change property of CSS:

    #target {
      will-change: transform;
    }
    Copy the code

    For details on the Composite layer, go to wireless performance optimization: Composite

Let’s talk about process 304

  • A. When a browser requests a resource, it first matches the Expires and cache-control sets of the resource. Expires is limited by the local time. Max-age specifies the maximum lifetime. 200 is still returned, but no data is requested. From cache is clearly visible in the browser.
  • B. Strong cache failure, enter the negotiation cache stage, first verify ETagETag can ensure that each resource is unique, resource changes will lead to changes in ETag. The server checks whether the cache is hit based on the if-none-match value sent by the client.
  • C. In the negotiation cache last-modify/if-modify-since phase, when a client requests a resource for the first time, the server adds last-modify to the header returned by the client. Last-modify indicates the time when the resource was Last modified. When the resource is requested again, the request header contains if-modify-since, which is the last-modify returned before the cache. After receiving if-modify-since, the server determines whether the resource matches the cache based on the last modification time.

The browser’s caching mechanism enforces caching && negotiation caching

The browser communicates with the server in reply mode, that is, the browser initiates an HTTP request and the server responds to the request. After the browser sends the request to the server for the first time and gets the request result, it decides whether to cache the result or not according to the cache identifier of the HTTP header in the response packet. If yes, the request result and cache identifier are stored in the browser cache. The simple process is as follows:

From the figure above, we can know:

  • Every time the browser makes a request, it willThe result of the request is first looked up in the browser cache along with the cache id
  • Every time the browser gets the result of the returned requestStore the result and the cache id in the browser cache

These two conclusions are the key to the browser cache mechanism, which ensures that every request is cached and read. Once we understand the browser cache rules, all the problems will be solved. For ease of understanding, the caching process is divided into two parts, namely mandatory caching and negotiated caching, depending on whether an HTTP request needs to be re-sent to the server.

  • Mandatory cache

    Forced caching is the process of looking up the result of a request to the browser cache and deciding whether to use the cached result based on the result’s caching rules. When the browser sends a request to the server, the server returns the Cache rule in the HTTP header of the HTTP response packet together with the request result to the browser. The fields that Control the mandatory Cache are Expires and cache-Control, respectively. Cache-control has a higher priority than Expires.

    There are three main cases of forced caching (the negotiation cache process is not analyzed), as follows:

    1. If the cache result and cache id do not exist, the cache is forcibly invalidated, and the request is directly sent to the server (the same as the first request).
    2. The cache result and cache id exist, but the result is invalid. If the cache is forced to become invalid, the negotiated cache is used.
    3. If the cache result and cache ID exist and the cache result is not invalid, the cache is forced to take effect and the cache result is returned directly
  • Negotiate the cache

    After negotiation cache cache invalidation is mandatory, the browser cache to carry identity requests to the server, the server according to the process of using cache cache id to decide whether, likewise, consultation of the cache logo is in response to a message HTTP headers and request results returned to the browser, cache control consultation fields are: Last-modified/if-modified-since and Etag/if-none-match, where Etag/if-none-match has a higher priority than last-modified/if-modified-since. The negotiated cache has the following two cases:

    1. Negotiation cache takes effect, return 304
    2. Negotiation cache invalid, returns 200 and request result

☞ Understand the browser caching mechanism thoroughly

Talk about processes, threads, and coroutines

Process is a dynamic execution process of a program with certain independent functions in a data set. It is an independent unit of the operating system for resource allocation and scheduling. It is the carrier of application program operation. Process is an abstract concept and there has never been a unified standard definition.

Thread is a single sequence control flow in program execution. It is the smallest unit of program execution flow and the basic unit of processor scheduling and dispatching. A process can have one or more threads that share the memory space of the program (that is, the memory space of the process in which it is running). A standard thread consists of a thread ID, the current instruction pointer (PC), registers, and a stack. A process consists of memory space (code, data, process space, open files) and one or more threads.

Coroutines, or “Coroutines”, are threads based on threads, but lighter than threads. These lightweight threads managed by programmers themselves are called “user-space threads” and have features that are invisible to the kernel.

The difference and connection between processes and threads

【 Distinction 】 :

Scheduling: thread as the basic unit of scheduling and allocation, process as the basic unit of owning resources;

Concurrency: Concurrent execution can be performed not only between processes, but also between multiple threads of the same process.

Owning resources: A process is a separate unit that owns resources. Threads do not own system resources, but can access resources belonging to the process.

Overhead: When a process is created or destroyed, the overhead is significantly higher than when a thread is created or destroyed because the system allocates and reclaims resources for it. However, processes have independent address space, a crash of a process in protected mode does not affect other processes, and threads are just different execution paths in a process. Thread has its own stack and local variables, but there is no separate address space between threads, a process dead is equal to all threads dead, so multi-process procedures than multithreaded procedures robust, but in the process switch, the cost of resources is larger, the efficiency is poor.

【 Contact 】 :

A thread can only belong to one process, and a process can have multiple threads, but at least one thread;

Resources are allocated to a process, and all threads of the same process share all resources of the process;

The processor is assigned to threads, that is, what is really running on the processor is threads;

Threads need to cooperate in synchronization during execution. Synchronization between threads of different processes is achieved by means of message communication.

☞ Learn more

HTML && CSS

HTML5 new features, semantic

  1. Concept:

    Semantic HTML5 refers to the proper use of semantic tags to create a page structure. The right label to do the right thing

  2. Semantic tags:

    header nav main article section aside footer

  3. Advantages of semantic:

    • inThe overall structure of the page looks good without CSS styles
    • Clear code structureEasy to read,
    • It facilitates development and maintenanceFacilitate parsing by other devices (such as screen readers) to render web pages semantically.
    • Search engine optimization (SEO) benefits, the search engine crawler will give different weights according to different tags

CSS selector and priority

The selector

  • Id selector (# myID)
  • Class selector (.myClass)
  • Attribute selector (a[rel=”external”])
  • Pseudoclass selector (A :hover, Li :nth-child)
  • Tag selector (div, H1, P)
  • Adjacent selector (H1 + P)
  • Child selector (UL > LI)
  • Descendant selector (Li A)
  • Wildcard selector (*)

Priority:

  • ! important
  • Inline style (1000)
  • ID selector (0100)
  • Class selector/Property selector/Pseudo-class selector (0010)
  • Element selector/Pseudoelement Selector (0001)
  • Relational selector/Wildcard selector (0000)

Take! The style attribute of the important tag has the highest priority; The stylesheet comes from the same source:! Important > Inline Style >ID selector > Class selector > Tags > Wildcards > Inheritance > Browser default properties

What the value of the position property is and how it differs

Fixed: The element’s position is fixed relative to the browser window, and it does not move even if the window scrolls. Fixed Makes the position of an element independent of the document flow and therefore does not take up space. Fixed positioned elements overlap with other elements.

Relative position: If an element is positioned relative to it, it will appear in its position. The element can then be moved “relative” to its starting point by setting its vertical or horizontal position. When relative positioning is used, elements still occupy the same space, whether or not they are moved. Therefore, moving an element causes it to overwrite other boxes.

Absolute: The position of an absolutely positioned element relative to its nearest positioned parent, if the element has no positioned parent, then its position relative to. Absolute positioning makes the position of an element independent of the document flow and therefore does not take up space. Absolute Positioned elements overlap with other elements.

Sticky localization: An element is first positioned according to the ordinary document flow, and then positioned relative to the flow root (BFC) and containing block (the nearest block-level ancestor element) of the element in the flow. Element positioning is then represented by relative positioning before crossing a specific threshold, followed by fixed positioning.

Default location Static: the default value. Without positioning, the element appears in the normal stream (ignoring the top, bottom, left, right or Z-index sound). Inherit: Specifies that the value of the position property should be inherited from the parent element.

The box – sizing properties

Box-sizing: content-box/border-box/inherit

Content-box: The width and height are applied to the element’s content box, respectively, drawing the inside margin and border of the element beyond the width and height. 【 Standard box model 】

Border-box: The width and height set for the element determines the border box of the element. 【IE Box model 】

Inherit: Inherit the box-sizing value of the parent element.

CSS box model

The CSS box model is essentially a box that contains: margins, borders, padding, and actual content. The box model in CSS includes IE box model and standard W3C box model. In the standard box model, width refers to the width of the content part. In the IE box model, width represents the width of content+padding+border.

Therefore, there are differences in calculating the width of the box:

Standard box model: Total width of a block = width+margin +padding +border

Weird box model: total width of a block = width+margin (width already includes the padding and border values)

BFC (Block-level Format Context)

The concept of landing

BFC stands for Block Formatting Context. BFC is a concept of CSS layout. It is a separate rendering area that specifies how the inner box is laid out, and the child elements of this area do not affect the outer elements. The most important layout rules are that the inner box is placed vertically, and floating elements are also involved in calculating the height of the BFC.

BFC layout rules

  • The internal Box will be inThe vertical directionAnd put them one by one
  • BoxThe vertical distance is determined by margin. Margins of two adjacent boxes belonging to the same BFC will overlap
  • The left side of the margin box of each element touches the left side of the border box containing the block (for left-to-right formatting, otherwise the opposite)
  • The landing areaDoes not overlap with float boxes
  • BFC is a separate container, inside the containerThe child elements do not affect the outside elements
  • When calculating the height of the BFC,Floating elements are also involved in calculating height
  • The type andThe display property determines the type of Box. Different types of boxes will participate in differentFormatting Context.

How do I create a BFC?

  • The root element, the HTML element
  • The value of float is not None
  • Position is absolute or fixed
  • The display value is inline-block, table-cell, and table-caption
  • The value of overflow is not visible

BFC application scenarios

  • Remove margin overlap
  • Clear the float (make the height of the parent element contain the child float element)
  • Prevents an element from being overwritten by a floating element
  • Avoid multi-column layouts that wrap automatically due to rounded width calculations

Center an element horizontally and vertically

  • Horizontal center

    • For inline elements: text-align: center;

    • For block-level elements of fixed width:

      (1) Width and margin implementation. margin: 0 auto;

      (2) absolute position and margin-left: -width/2, if the parent element position: relative

    • For block-level elements of unknown width

      (1) The table label achieves horizontal center with left and right Auto margin. Use the table tag (or simply set the block-level element to display:table) and add a margin of auto to the tag.

      (2) Inline-block implements horizontal center method. Display: inline-block and text-align:center achieve horizontal center.

      (3) Absolute positioning + Transform, translateX can move 50% of its element.

      (4) Flex layout uses context-content :center

  • Vertical center

    1. usingline-heightImplementation center, this method is suitable for pure text classes
    2. By setting parent container relative positioning, child settingAbsolute positioning, the label realizes adaptive center through margin
    3. Display: flex; Sub-set margin to auto to achieve adaptive center
    4. Relative positioning is set for the parent level, and absolute positioning is set for the child level, which is realized by displacement transform
    5. The table layoutBy converting to table form,Then the child set vertical-align implementation. (Note that vertical-align: middle is used only for the inline element and the element whose display value is table-cell.)

CSS horizontal and vertical center common interview methods

A method to hide an element in a page

Opacity: 0: this element is hidden, but does not change the page layout. Also, if the element is already bound to some events, such as click events, clicking on this area can also trigger click events

2. Visibility: hidden, will not change the page layout, but will not trigger the binding event of the element, hide the corresponding element, and leave the original space in the document layout (redraw).

3. Display: None: hides the element and changes the layout of the page. Do not show corresponding elements, no more space allocated in document layout (reflux + redraw)

This problem leads to backflow and redraw

Use CSS to implement trigonometric symbols

/* Memory tip: the width and height of the box are zero, and the three sides of the box are transparent. * /
div:after{
    position: absolute;
    width: 0px;
    height: 0px;
    content: "";
    border-right: 100px solid transparent;
    border-top: 100px solid #ff0;
    border-left: 100px solid transparent;
    border-bottom: 100px solid transparent;
}
Copy the code

The page layout

1. The Flex layout

The traditional solution to layout, based on the box model, relies on the display property + position property + float property. It is very inconvenient for special layouts, such as vertical center, which is not easy to implement.

Flex, short for Flexible Box, is designed to provide maximum flexibility to Box models. Specify the container display: flex. There are simply container attributes and element attributes.

Container properties:

  • Flex – direction: the direction of the spindle (i.e., the son of item arrangement method) flex – direction: row | row – reverse | column | column – reverse;
  • The flex – wrap: decided to break rules flex – wrap: nowrap | wrap | wrap – reverse;
  • The flex – flow: box {flex – flow: | |. }
  • Illustration-content: The alignment of the horizontal principal axis to its mode
  • Align-items: indicates the alignment mode of the vertical axis
  • align-content

Project attributes (element attributes) :

  • Order property: defines the order of items, the smaller the order, the higher the order. Default is 0
  • Flex-grow property: Defines the scale to which the project will not be enlarged, even if there is space
  • The flex-shrink attribute: defines the rate at which the item is shrunk. If the flow-shrink value of an item is set to 0, it is not shrunk
  • The flex-basis property: defines the amount of space that an item occupies when allocating excess space.
  • Flex: short for flex-grow, flex-shrink, and flex-basis. The default value is 0. 1 Auto.
  • Align-self: Allows a single item to be aligned differently from other items and can be overridden
  • Align-items, whose default ownership is auto, inherits the parent element’s align-items for example, the Holy Grail layout in Flex

2. Rem layout

First, the Rem font size relative to the root (HTML) is calculated. Font-size :10px; (1rem = 10px) How to set the font size of HTML on different devices. In fact, the essence of REM layout is proportional scaling, generally based on width.

Advantages: Can quickly adapt mobile layout, font, image height

Disadvantages:

(1) The current IE does not support, the use of PC pages is not much; ② Large amount of data: all pictures and boxes need us to give an accurate value; To ensure the adaptation of different models; 3) In a responsive layout, you must use JS to dynamically control the size of the root element font size. That is, there is some coupling between CSS styles and JS code. The code that changes font size must precede the CSS style.

3. Percentage layout

A responsive effect is achieved by the percentage unit “%”. Percentage units allow the width and height of the components in the browser to change with the browser to achieve a responsive effect. Intuitively, we might think that the percentage of the child element is completely relative to the immediate parent element, the height percentage is relative to height, and the width percentage is relative to width. Padding, border, margin, and so on, both vertically and horizontally, are relative to the width of the immediate parent element. In addition to border-radius, translate, background-size, etc. are relative to themselves.

Disadvantages:

(1) Calculation difficulty (2) If percentages are used in each attribute, the attribute relative to the parent element is not unique. The layout problem is easily complicated by our use of percentage units.

4. Floating layout

Floating layout: When an element is floating, it can move left or right until its outer edge touches the border of the box that contains it or another floating element. Elements float out of the normal flow of the document, so the box in the normal flow of the document becomes as if the floating element did not exist.

advantages

The advantage of this method is that it is good to surround the image with text when mixing images. In addition, when an element is floated, it has some block-level properties such as the ability to set the width, but there are some differences between it and inline-block. The first is that for horizontal sorting, float can set the orientation while inline-block orientation is fixed. Another problem is that inline-blocks sometimes have a white space when used

disadvantages

The most obvious disadvantage is that the floating element cannot support the parent element once it is out of the document flow, causing the parent element to collapse very high.

How to use REM or ViewPort for mobile adaptation

Rem adaptation principle:

Changes the number of CSS pixels an element occupies on different devices

Pros and cons of REM adaptation

  • Pros: No damage to the perfect viewport
  • Disadvantages: Rem px conversion is too complex (let’s use less to solve this problem)

Principle of ViewPort adaptation

In viewport adaptation, each element occupies the same number of CSS pixels on different devices. But the ratio of CSS pixels to physical pixels is not the same, equal ratio

Advantages and disadvantages of Viewport adaptation

  • The size measured on our drawing is the pixel size that we can set, that is, the amount is set
  • Defects destroy the perfect viewport

The way to clear the float

  • Add extra labels
<div class="parent">// Add additional labels and add the clear attribute<div style="clear:both"></div>// You can also add a br tag</div>
Copy the code
  • The parent adds overflow properties, or sets the height
  • Create a pseudo-class selector to clear the float
// Add :after pseudo-element to CSS
.parent:after{
    /* Sets the content of the added child element to empty */
    content: ' ';
    /* Set add child element to block level element */
    display: block;
    /* Sets the height of the added child element to 0 */
    height: 0;
    /* Sets add child element invisible */
    visibility: hidden;
    /* Set clear: both */
    clear: both;
}
Copy the code

JS, TS, ES6

8 data types and differences in JS

Includes value types (basic object types) and reference types (complex object types)

Basic types (value types) : Number,String,Boolean,Symbol,null,undefined Occupy a fixed size in memory and are stored in stack memory

Reference types (complex data types) : Object, Function. Other reference types such as Array, Date, RegExp, special primitive wrapper types (String, Number, Boolean), and single built-in objects (Global, Math) are stored in heap memory. Stack memory stores the variable identifier of the object and the storage address of the object in heap memory.

JS data type detection scheme

1.typeof

console.log(typeof 1);               // number
console.log(typeof true);            // boolean
console.log(typeof 'mc');            // string
console.log(typeof function(){});    // function
console.log(typeof console.log());   // function
console.log(typeof []);              // object 
console.log(typeof {});              // object
console.log(typeof null);            // object
console.log(typeof undefined);       // undefined
Copy the code

Advantages: Ability to quickly distinguish between basic data types

Disadvantages: Object, Array, and Null cannot be distinguished; all return Object

2.instanceof

console.log(1 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true
Copy the code

Advantages: Can distinguish Array, Object, and Function, suitable for judging custom class instance objects

Disadvantages: Number, Boolean, String Basic data type cannot be determined

3.Object.prototype.toString.call()

var toString = Object.prototype.toString;
console.log(toString.call(1));                      //[object Number]
console.log(toString.call(true));                   //[object Boolean]
console.log(toString.call('mc'));                   //[object String]
console.log(toString.call([]));                     //[object Array]
console.log(toString.call({}));                     //[object Object]
console.log(toString.call(function(){}));           //[object Function]
console.log(toString.call(undefined));              //[object Undefined]
console.log(toString.call(null));                   //[object Null]
Copy the code

Advantages: Accurate judgment of data types

Disadvantages: cumbersome writing method is not easy to remember, recommend packaging after use

var && let && const

Before ES6, variables were created using var. After ES6 variables were created using let/const

Three differences:

  1. The variable defined by var,There is no concept of blocks and access across blocksCannot be accessed across functions.

    Variables defined by lets can only be accessed in the block scope, not across blocks or functions.

    Const is used to define constants, must be initialized (that is, must be assigned), can only be accessed in the block scope, and cannot be modified.
  2. Var can beUse first, declare later, because there is variable promotion; Let must be spoken before use.
  3. Var is allowed in the same scopeDeclare the same variable repeatedlyLet and const do not allow this.
  4. In the global context, global variables based on let declarations have nothing to do with the global object GO (window); Var declares variables that map to GO.
  5. Temporary dead zones are created:

Log (typeof a) //undefined will not be returned when checking for an undeclared variable type. Console. log(typeof a)// Let a cannot be used without a declaration

  1. Let /const/function uses curly braces (except for functions) as a new block-level context. With this mechanism, you don’t need to build closures to store looped event bindings and the like when developing projects

JS garbage collection mechanism

  1. Page performance can be slow if there is a large amount of memory (heap/stack/context) in a project that is not being freed. Memory leaks occur when certain code operations cannot be freed properly. We use closures as little as possible because they consume memory.

  2. Browser garbage collection mechanism/memory collection mechanism:

    Javascript in browsers has automatic Garbage Collecation, where the Garbage collector periodically (periodically) finds variables that are no longer in use and then frees their memory.

    Tag cleanup: In JS, the most common garbage collection mechanism is tag cleanup: variables are marked “in” when they enter the execution environment, and “out” when they leave the execution environment. The garbage collector destroys the tagged values and reclaims the memory they occupy. Google Chrome: “find references”, the browser periodically looks for references to the current memory, if not occupied, the browser will reclaim it; If it is occupied, it cannot be recycled. IE browser: “reference counting method”, the current memory is occupied once, count the accumulation of 1, remove the occupied on the reduction of 1, when reduced to 0, the browser will reclaim it.

  3. Optimization means: memory optimization; Manual release: Cancel the memory usage.

    (1) fn = null

    (2) Stack memory: in the context, the external occupation of the heap can be cancelled.

  4. A memory leak

    In JS, there are four common memory leaks: global variables, closures, DOM element references and timers

Scope and scope chain

When a function is created, the scope of the current function is declared ==> the context in which the current function is created. [[scope]]:EC(G); [scope]]:EC(G); [scope] :EC(G);

Definition: Simply put, a scope is the accessible range of variables and functions, consisting of a series of variable objects in the current environment and the upper environment 1. Global scope: Code can be accessed anywhere in the program. The built-in properties of the Window object have global scope. 2. Function scope: only a fixed code fragment can be accessed

Effect: The greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.

In general, a variable takes a value to the scope of the function that created the variable. But if it is not found in the current scope, the chain is called the scope chain.

Closures do two things: save/protect

  • The concept of closures

    The private context EC(FN) formed during the execution of the function. Under normal circumstances, the code will be released after the execution of the stack. However, in the special case, if something in the current private context is occupied by something outside the context, the context will not be released from the stack, resulting in an undestroyed context. Function execution During the execution of a function, a new private context is created, which may or may not be released.

(1) Protection: divide an independent code execution area, have their own private variable storage space in this area, protect their own private variables from external interference (operate their own private variables and the outside world has no relationship);

(2) Save: if the current context is not freed (as long as something in the context is occupied by the outside), then the stored private variables are not freed and can be used by the lower context, equivalent to saving some values;

The mechanism for protecting and storing private variables is called closures.

A closure is a function that has access to a variable in another function’s scope.

A more comprehensive answer: In JS, the scope of a variable belongs to the function scope. After the function is executed, the scope will be cleaned up and the memory will be reclaimed. However, since the closure function is a sub-function built inside the function and can access the upper scope, the scope will not be destroyed after the upper function is executed. The child function (that is, the closure) has access to the variables in the parent scope, and the values in the scope are not destroyed even after the parent function has finished executing.

  • Closure features:

    • 1. Inner functions have access to the parameters and variables that define their outer functions. (Lookup up the scope chain, storing the values of variables in the outer scope in memory rather than destroying them after the function is called) Design private methods and variables to avoid contamination of global variables.

      1.1. Closures are closed containers, similar to set and Map containers, that store data

      1.2. A closure is an object that stores data in a key-value format

    • 2, function nested function

    • The essence is to connect the inside and outside of a function. The advantage is that you can read variables inside a function, keeping their values in memory at all times and not clearing them automatically after the function is called

  • Conditions for closure formation:

    1. Nesting of functions
    2. The inner function references the local variables of the outer function, extending the variable life cycle of the outer function
  • Closures are useful for:

    1. Mimic block-level scopes
    2. A variable that protects an external function can access the lexical scope in which the function was defined (to prevent it from being reclaimed)
    3. Encapsulate privatization variables
    4. Create a module
  • Closure application scenarios

    Two scenarios for closures, two main uses of closures: save/protect. Closures are ubiquitous in development, and most of the front-end JavaScript code is “event-driven”, meaning an event-bound callback method; To send an ajax request success | failure callback; SetTimeout delay callback; Or a function that returns another anonymous function inside of it, those are all applications of closures.

  • Advantages of closures: Prolong the life of local variables

  • Disadvantages of closures: Function variables can be kept in memory, and too many closures can cause memory leaks

Five cases of this in JS

  1. When executed as a normal function,thisPoint to thewindow.
  2. When a function is called as a method of an object,thisCan point toThe object.
  3. Constructor call,thisPoint to theThis object is returned.
  4. Arrow function of the arrow functionthisBinding looks atWhich object is under which this function is defined, which object is bound to. If there is nesting, this is bound to the nearest layer object.
  5. Prototype based on FunctionApply, call and bindAll three methods can display the this pointer to the specified calling function.applyThe parameters are arrays,callAccept a list of arguments, ‘bind’Method returns an object by passing in an object this A new function that binds the passed object. Of this functionthisPoint to besides useIt will be changed when it’s new, and it won’t be changed otherwise. If null, the default is to point to the global object Window.

Prototype && Prototype chain

Archetypal relationship:

  • Each class has a prototype display
  • Each instance has an implicit stereotype _ proto_
  • The _ proto_ of the instance points to the prototype of the corresponding class

Prototype: In JS, whenever an object (function is also an object) is defined, the object contains predefined properties. Each of these function objects has a Prototype property that points to the function’s prototype object.

The constructor of a function’s prototype chain object points to the function itself by default. In addition to having prototype properties, for inheritance purposes, the prototype chain object has a __proto__ pointer that points to the prototype object at the next level, which remains similar in structure. Therefore, __proto__ can be used to point to the prototype Object all the time, and the prototype Object uses object.prototype. __proto__ = null to indicate the top of the prototype chain. Thus formed the js prototype chain inheritance. At the same time, all JS objects have the basic defense of Object

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

The implementation mechanism of the new operator

  1. First, a new one is createdAn empty object
  2. Set the prototype, sets the prototype of the object to functionprototypeObject.
  3. Let the function of thethisPoint to the object and execute the constructor code (add attributes to the new object)
  4. Determine the return value type of the function and, if it is a value type, return the created object. If it is a reference type, an object of that reference type is returned.

EventLoop indicates an EventLoop

JS is single-threaded, in order to prevent a function the code behind the blocked the execution time is too long, so will try to press the synchronization code into execution stack, in turn, push the asynchronous code into the asynchronous queue, asynchronous queue is divided into macro task queue and task queue, because the macro task queue execution time is longer, so the task queue to priority has been the task queue. Then, MutationObserver, and setImmediate setTimeout setInterval for macro tasks

The environment in which JS runs. Usually a browser or Node. In the browser environment, there are JS engine threads and rendering threads, and the two threads are mutually exclusive. In a Node environment, there are only JS threads. Different execution mechanisms vary in different environments. Different tasks enter different Event queues. When the main procedure ends, the ready microtask is performed, followed by the ready macro task, and a poll is completed.

Event loops in browsers

The operation mechanism of the event loop is that the contents in the stack will be executed first, then the micro task will be executed after the contents in the stack are executed, and then the macro task will be executed after the micro task is cleared. First, a macro task will be removed, then the micro task will be executed, and then the macro task will be removed and the micro task will be cleared.

  • EventLoop is implemented by the JS host environment (browser);

  • The event cycle can be simply described as the following four steps:

    1. When an asynchronous task is executed in the Stack, it is dumped to the WebAPIs, and the synchronous task is executed until the Stack is empty.
    2. In the meantime, WebAPIs complete the event and queue the callback function for execution (microtask on microtask queue, macro task on macro task queue).
    3. When the stack is empty, the Event Loop clears the microtask queue.
    4. After the microtask queue is empty, enter the macro task queue and put the first task in the queue into the Stack(Stack) for execution. After the execution, check whether there is any task in the microtask queue. If so, clear the microtask queue. Repeat 4, continue to take tasks from the macro task to execute, after completion, continue to clear the micro task, and so on until all tasks are cleared.

  • Task sources in the browser:

    • Macro task (macrotask):

      Provided by the host environment, such as a browser

      Ajax, setTimeout, setInterval, setTmmediate(IE only), Script, requestAnimationFrame, messageChannel, UI rendering, some browser apis
    • Micro tasks (microtask):

      The language itself provides, such as promise.then

      Then, queueMicrotask(based on THEN), mutationObserver(provided by the browser), messageChannel, mutationObersve

Event Loop in Node environment

Node is a server-side JavaScript environment based on the V8 engine. It has obvious advantages in high concurrency and I/O intensive (file operation, network operation, database operation, etc.) scenarios. Although the V8 engine is used, its API is somewhat different from native JS due to different service purposes and environments. Its Event Loop also needs to handle some I/O, such as new network connections, so the Event Loop mechanism of Node is different from that of browser.

The execution sequence is as follows:

  • timers: a timer that performs callbacks to setTimeout and setInterval
  • pending callbacks: Performs I/O callbacks deferred until the next iteration of the loop
  • idle, prepare: Queue movement, for internal use only
  • Poll polling: Retrieves new I/O events; Perform I/ O-related callbacks. In fact, almost all asynchrony is handled in this phase, except for a few other phases.
  • check: performsetImmediateCallback, setImmediate executes here
  • close callbacks: performcloseThe eventcallback, some closed callback functions such as socket.on(‘close’,…)

SetTimeout, Promise, Async/Await

  1. setTimeout

    The setTimeout callback is placed in the macro task queue until the stack is empty.

  2. Promise

    Promise itself is a synchronous execute now function. When resolve or Reject is executed in an executor, it is an asynchronous operation, executing then/catch, etc., and then calling the resolve/ Reject method when the main stack is complete.

    console.log('script start')
    let promise1 = new Promise(function (resolve) {
        console.log('promise1')
        resolve()
        console.log('promise1 end')
    }).then(function () {
        console.log('promise2')})setTimeout(function(){
        console.log('settimeout')})console.log('script end')
    // Output sequence: script start->promise1->promise1 end->script end->promise2-> setTimeout
    Copy the code
  3. async/await

    An async function returns a Promise object. When the function executes, it returns an await and waits until the triggered asynchronous operation is complete before executing the following statement in the function body. It can be understood as giving up the thread, out of the async function body.

    async function async1(){
       console.log('async1 start');
        await async2();
        console.log('async1 end')}async function async2(){
        console.log('async2')}console.log('script start');
    async1();
    console.log('script end')
    
    // Output order: script start->async1 start->async2->script end->async1 end
    Copy the code

How can Async/Await be asynchrony

Async/Await is a self-executing generate function. Use the feature of generate to write asynchronous code in the form of “synchronous”, with the return value of the first request as the parameters of the subsequent request, each of which is a promise object.

Introduce the principle, difference and application of throttling and anti – shake

Throttling: After an event is triggered, event handlers cannot be called again for a specified period of time. That is, a function can only be called once in a given amount of time, and it is the first time that the call is triggered.

The event handler can only execute once and at the end of the trigger operation. That is to say, when an event is triggered to perform before the event functions, will wait for a certain amount of time (this time to code, is defined, such as 1 second), if not be triggered again, then, if you are triggered, then the invalid, to trigger a new starting time, and again wait a second, until the final execution!

Usage scenarios: Throttling: scroll to load more, search box search associative function, high-frequency click, repeat form submission…… Anti – shake: search box search input, and after the input of automatic search, mobile phone number, mailbox verification input detection, window size resize changes, and then re-render.

/** * The throttling function executes a function once, and only executes it a second time after the specified execution period. There is a function that needs to fire frequently. In order to optimize performance, only the first function that fires is allowed to take effect within a specified period of time, and subsequent functions are not allowed to take effect. *@param Fn the function to be throttled *@param Delay Specifies the time */
function throttle(fn, delay) {
    // Record the last time the function fired
    var lastTime = 0;
    return function(){
        // Record the time when the current function fires
        var nowTime = Date.now();
        if(nowTime - lastTime > delay){
            // Fix this pointing problem
            fn.call(this);
            // Synchronization end timelastTime = nowTime; }}}document.onscroll = throttle(function () {
    console.log('Scllor event triggered' + Date.now());
}, 200); 

/** * A function that needs to be triggered frequently, within a specified period of time, only the last time, the preceding does not take effect *@param Fn the function to be throttled *@param Delay Specifies the time */
function debounce(fn, delay) {
    // Record the last delay
    var timer = null;
    return function () {
       // Clear the last demonstrator
        clearTimeout(timer);
        // Reset the new delay timer
        timer = setTimeout(function(){
            // Fix this pointing problem
            fn.apply(this); }, delay); }}document.getElementById('btn').onclick = debounce(function () {
    console.log(The button was clicked. + Date.now());
}, 1000);
Copy the code

Briefly describes the MVVM

What is MVVM?

ViewModel bidirectional binding, which is short for 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 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. It used to be a DOM structure update view, but now it’s a data-driven view.

Advantages of MVVM:

1. Low coupling. A View can be changed and modified independently of the Model. A Model can be bound to different views. When the View changes, the Model can not change, and when the Model changes, the View can not change. 2. Reusability. You can put some View logic in a Model and have many views reuse that View logic. 3. Develop independently. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design. 4. Testable.

Underlying implementation principles of Vue

Vue is a typical MVVM framework that uses data hijacking combined with the publisheer-subscriber pattern. It uses Object.defineProperty() to hijack the setter and getter of each attribute, publish messages to subscribers when data changes, and trigger corresponding listener callback. A Model is just a normal javascript object, and modifying it will update the View automatically. This design makes state management very simple and intuitive

Observer (data listener) : The core of the Observer is to listen for changes in data through Object.defineProprtty(). This function defines setters and getters inside and fires setters whenever data changes. At this point, the Observer informs the subscriber, who is Watcher

Watcher (Subscriber) : The Watcher subscriber acts as a communication bridge between the Observer and Compile.

  1. Add yourself to the attribute subscriber (DEP) during self instantiation
  2. There must be an update() method itself
  3. It can call its own update() method and trigger the callback bound in Compile when notified of property changes to dep.notice()

Compile (instruction parser) : Compile mainly does is to parse the template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add identify the data subscribers, once the data changes, receive notification, update attempts

What is your understanding of the VUE lifecycle?

Each Vue instance is created through a series of initializations. Vue lifecycle hooks are functions that are triggered when a certain stage or condition is reached in order to complete some action or event

  • The create phase: The vue instance is created

    beforeCreate: Before creation, data in data and methods has not been initialized

    createdData contains a value but is not mounted
  • Mount stage: Vue instances are mounted to real DOM nodes

    beforeMount: can initiate server requests to go to data

    mounted: DOM can be manipulated
  • The update phase: Triggers component re-rendering when data in the vue instance changes

    beforeUpdateBefore the update:

    updatedAfter the update:
  • Destroy stage: The vue instance was destroyed

    beforeDestroyMethods can be manually destroyed at this point before the instance is destroyed

    destroyed: after destruction

Component life cycle

Life cycle (Parent and child) Parent beforeCreate –> Parent created –> Parent beforeMount –> child beforeCreate –> child created –> child beforeMount –> Child created –> Child beforeMount –> Child component mounted –> Parent component mounted –> Parent component beforeUpdate –> child component beforeDestroy–> Child component destroyed –> Parent component updated

Load render process parent beforeCreate-> Parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> child Mounted -> Parent Mounted

Mounted phase Parent created-> child created-> child mounted-> parent mounted

Parent component Update phase parent beforeUpdate-> Parent updated

Child component update phase Parent beforeUpdate-> child beforeUpdate-> Child updated-> Parent updated

Parent beforeDestroy-> Child beforeDestroy-> Child destroyed-> Parent destroyed

Computed with the watch

In general terms, things that can be done with computed and things that can be done with watch, computed is recommended, but the important thing about computed is that computed caching is used to declaratively describe a value that depends on something else, When the dependent value or variable changes, the calculated attribute changes with it; Watch listens to variables already defined in data, and when that variable changes, methods in Watch are triggered.

The watch attribute listener is an object, the key is the attribute to be observed, and the value is the corresponding callback function. It is mainly used to monitor the change of some specific data, so as to carry out some specific business logic operations, and monitor the change of attributes. It needs to be used when asynchronous or expensive operations are performed when data changes

The results of attributes computed are cached, and when the attributes on which the computed function depends do not change, the results are read from the cache when the current function is called. Unless recalculated, functions that use computed primarily as attributes must return the final result for computed efficiency, which is preferred. Data doesn’t change, computed doesn’t update.

Usage Scenario Computed: Used when an attribute is affected by multiple attributes, for example, shopping cart billing function Watch: used when one data affects multiple attributes, for example, searching data

Why is data in a component a function?

1. When a component is reused multiple times, multiple instances are created. Essentially, these instances all use the same constructor. 2. 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.

Why are v-for and V-if not recommended together

1. When v-for and V-if are on the same node, v-for has a higher priority than V-if, which means that V-IF will run separately in each V-for loop. This can be a significant performance waste if the array to be traversed is large and the actual data to be presented is small 2. In this scenario, it is recommended to use computed data filtering first

React/Vue project key functions

  • The function of key is to find the corresponding node faster during the execution of diFF algorithm, improve the speed of DIFF, and update virtual DOM more efficiently.

    Both VUE and React use the diff algorithm to compare old and new virtual nodes to update nodes. In the diff function of vue, it compares the key of the old node array according to the key of the new node to find the corresponding old node. If it is not found, it is considered a new node. If there is no key, a traversal lookup is used to find the corresponding old node. One is a map, and the other is a traversal search. By comparison. Map enables faster mapping.

  • To force component updates as data changes to avoid the side effects of in-place reuse.

    When vue.js updates a rendered element list with V-for, it defaults to a “reuse in place” strategy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element here and make sure it shows every element that has been rendered under a specific index. Duplicate keys cause render errors.

Communication mode of VUE components

  • Props /$emit parent-child component communication

    Parent -> props, child -> parent $on, $emit get parent component instances parent, children Ref get instance methods parent -> descendants Provide, inject

  • $emit/$ON custom event sibling component communication

    Prototype.$Bus = new Vue() custom Event

  • Vuex cross-level component communication

    Vuex, $listeners Provide, $listeners Provide, inject

The realization of the nextTick

  1. nextTickisVueProvides a global viewAPIIt will be next timeDOMA deferred callback is performed after the update loop is complete and is used after the data has been modified$nextTick, you can get the updated in the callbackDOM;
  2. Vue is executed asynchronously when updating the DOM. As long as I’m listening for changes in the data,VueA queue is opened and all data changes that occur in the same event loop are buffered. If the samewatcherIf triggered more than once, it will only be pushed into the queue once. This eliminates duplicate data during buffering to avoid unnecessary calculations andDOMOperation is very important.nextTickMethod adds a callback function to the queue, ensuring that it is not called until the previous DOM operation is complete.
  3. For example, when I’m doing something, I use nextTick, pass in a callback function, and perform DOM operations in it;
  4. I know a little bit about itnextTickImplementation, it will be incallbacksPut in the function that we passed in, and usetimerFuncCall them asynchronously, and the preferred asynchronous would bePromise. This makes me understand why it is possible to be innextTickseedomOperation result.

How does nextTick work?

A deferred callback is performed after the end of the next DOM update loop, and nextTick is used to retrieve the updated DOM immediately after the data is modified. NextTick mainly uses macro and micro tasks. Promise, MutationObserver, and setImmediate are used depending on the execution environment. If none of the above fails, setTimeout defines an asynchronous method, through which multiple calls to nextTick are queued to clear the current queue.

Have you ever used a slot? Is it a named slot or an anonymous or scoped slot

Slots in vUE are a very useful thing slot is basically a placeholder and there are three types of slots in VUE one is the default slot (anonymous) one is the named slot and one is the scoped slot and the anonymous slot is the one that doesn’t have a name as long as the defaults are filled in here the named slot is the one that has a name

Keep – the realization of the alive

Purpose: Implements component caching and keeps the state of these components to avoid performance problems caused by repeated rendering. The cache components need to be switched frequently without repeated rendering

Scenario: Background navigation of tabs, vUE performance optimization

Principle: Vue. Js internally abstracts DOM nodes into vNodes. The cache of keep-Alive components is also based on Vnodes rather than directly storing DOM structures. The pruneCache and pruneCache components are cached in the cache object, and vNodes are removed from the cache and rendered when needed.

mixin

Mixins are used when mixin projects get complicated and there is repeated logic between multiple components. Multiple components have the same logic, and pulling out mixins is not a perfect solution. There will be some problems. The Composition API proposed by VUe3 aims to solve these problems [perfection costs a certain amount of money, such as development costs] scenario: The right column of the NEWS list and details page on PC can be used for mixin. Disadvantages: 1. 2. Multiple mixins may cause naming conflicts. 3. Mixins and components may have a many-to-many relationship, resulting in high project complexity

Understanding and application scenarios of Vuex

Vuex is a state management mode developed specifically for Vue applications. At the heart of every Vuex application is the Store.

  1. Vuex’s state storage is responsive; When the Vue component reads the state from the Store,

If the state in the store changes, the corresponding components are updated efficiently. 2. The only way to change a state in a store is to explicitly commit mutation, which makes it easy to track every state change. Vuex consists of the following core modules:

  1. State: defines the status data of the application
  2. Getter: Defines the “Getter” in the store (think of it as a computed property of the store),

The return value of a getter is cached based on its dependency, and is recalculated only if its dependency value has changed. 5. Module: Allows a single Store to be broken up into multiple stores simultaneously stored in a single state tree

Project optimization

Remove console printing in production. There are many schemes, such as esling+pre-commit and automatic removal by plug-ins, including babel-plugin-transform-remove-console, Uglifyjs-webpack-plugin and terser-webpack-plugin. The terser-webpack-plugin is used to enable caching and multithreading packaging. There is no need to install additional plug-ins, just set the Drop_console of the Terser plugin to true in configureWebpack. It’s best to develop good code habits and remove useless consoles after development is basically complete. Vscode turbo console works fine.

On-demand loading of third-party libraries. Echarts, which is officially documented as using modules specified by configuration files, and babel-plugin-equire, which is loaded on demand. Element-ui uses babel-plugin-Component for on-demand import.

Common styles, such as uniform adjustments to the styles of elements in the Element-UI component (such as pop-ups, tables, drop-down boxes, etc.). Common components, such as date-picker, upload-file, and so on, are basically further encapsulated in the element UI component. Custom components include preview-file, search box, and so on.

In terms of data exchange at the front and back ends, I promoted the project team to use blue Lake and interface documents, and negotiated with students at the back end to standardize the return of background data.

Yahoo catch-22 mentioned, avoid CSS expressions, filters, less DOM operations, optimize pictures, Sprite graphs, avoid empty links, etc.

Performance issues: page loading performance, animation performance, operational performance. Performance API to record Performance data.

Technical solution of Winter relearning front-end optimization:

Caching: Client-controlled strong caching policy.

Reduce request cost: The DNS is controlled by the client and proactively requests for domain name IP addresses from time to time without going through the system DNS. TCP/TLS connections are multiplexed, servers are upgraded to HTTP2, and domain names are merged whenever possible.

Reduce the number of requests: JS and CSS are packaged into HTML. JS control image asynchronous loading, lazy loading. Use data-URI for small images.

Less transfer volume: Try to use SVG\gradient instead of images. Control image sharpness according to model and network condition. Sharpen low definition images to enhance the experience. Avoid large background images by design.

Using CDN acceleration, content distribution network is a virtual distributed network based on re-hosting network, which can cache source content to node servers nationwide or globally. Users can obtain content from nearby sites, which increases the speed of resource access and shares the pressure of source sites.