Haven’t update the post for a long time, has recently been reviewed for the autumn, the recent finally got the first letter of intent, finally have time to clean up his review of the current content, the following points are the problems of the original poster was asked during an interview, I made a few chunks of classification, you need a friend to collect it. Because the interview is still continuing, so it will be updated from time to time, because the nuggets side of the article has a word limit, so here released HTML part, CSS part, JS part of the knowledge, Vue, git, webpack, network related knowledge in the next article juejin.cn/post/687707… .

HTML part:

Classification of HTML tags:

HTML document tag

  1. <! DOCTYPE>: Defines the document type.

  2. <html>: Defines HTML documents.

  3. <head>: Defines the header of the document.

    <meta>: Defines the meta information that the element can provide about the page, such as descriptions and keywords for search engines and update frequency.

    metaThe tag has two attributes,http-equivProperties: Acts like an HTTP header that returns useful information to the browser, using content to specify properties such as

nameAttribute: mainly used to describe web pages, content is mainly convenient for search engine robots to find information and classification information.

<base>: Defines the default address or target for all links on the page.

<title>: Defines the document title.

<link>: Defines the relationship between documents and external resources.

<style>: Defines HTML document style information.

  1. <body>: Defines the body of the document. (The script is at the end when not required)

Classification by closed features:

  • A closed tag is a pair of tags made up of a start tag and an end tag that allows nesting and hosting of content, for example<html></html>,<p></p>And so on.
  • An empty label is a label that has no content and is automatically closed in the start label. Common empty labels are:<br>,<hr>,<img>,<input>,<link> <meta>.

Classification by newline feature or not:

  • Block-level elements: Block-level elements are elements whose values themselves have the attribute display:block.
  • Inline elements: An inline element is an element whose own attribute is display:inline, whose width varies with the content of the element.

Characteristics of block-level elements

  • Each block-level element occupies an exclusive row, arranged from top to bottom.
  • Block-level elements can directly control box model-related CSS properties such as width and height.
  • Without setting the width, the width of a block-level element is the width of the content of its parent element.
  • Without setting the height, the height of a block-level element is the height of its own content.
Common block-level elements:

Features of inline elements:

  • Inline elements are displayed on a line from left to right with other elements.
  • Inline elements do not directly control the width, height, and box-model-related CSS properties. You can set the horizontal value of the inner and outer margins. In other words, only margin-left/margin-right and padding-left/padding-right are valid for in-line elements. Vertical margin and pading have no effect.
  • The width and height of an inline element is determined by the size of its content itself.
  • Inline elements can only hold text or other inline elements. Block level elements are not allowed to be nested within inline elements.
Common inline elements:

H5 New features (common) :

HTML5 new elements:

Header section footer Aside Nav main article figure Mark Highlight Progress New form control Calander Date Time email Url search New input type Color Date Datetime datetime-local email Removed outdated tag Big Font Frame Frameset 2) Canvas drawing, support inline SVG. MathML 3) Multimedia Audio Video source Embed Track 4) Local offline storage, put the need for offline storage in the local file listed in a manifest configuration file 5) Web storage,localStorage, SessionStorage

Cookie sessionStorage localStorage

Name: indicates the Name of a Cookie. Value: indicates the Value of a Cookie. Indicates the domain name that can access the cookie. A second-level domain name can obtain the cookie in the top-level domain name. The top-level domain name cannot obtain the cookie Path field of the second-level domain name. Is the page path that can access the cookie, and only pages under this path can read the cookie Expires/ max-age field: If the timeout period of the cookie is set to a time, the cookie is invalid after this time is reached. If the timeout period is not set, the default value is Session, that is, the cookie is invalid after the browser is closed. Size field: indicates the Size of the cookie. HTTP field: indicates the Httponly property of the cookie. If this property is set to true, the cookie information is carried only in the HTTP request header and cannot be accessed through document.cookie. Secure field: Indicates whether this cookie can only be passed over HTTPS.

Cookies and webstorage:

  • Cookie data is always carried (even if it is not needed) in same-origin HTTP requests, i.e. cookies are passed back and forth between the browser and the server.
  • Cookie data also has the concept of a path, which can be restricted. Cookie data cannot exceed 4K. At the same time, cookies are only suitable for storing small data, such as call id, because each HTTP request carries cookies.
  • WebStorage, while limited in size, is much larger than cookies, up to 5M or more

SessionStorage and localStorage:

  • The validity period of data is different:

    • SessionStorage: only valid when the current browser window is closed;
    • LocalStorage: always valid, saved even when the window or browser is closed and therefore used as persistent data; Cookie: Only lasts until the set cookie expiration time, even if the window and browser are closed.
  • Different scopes:

    • SessionStorage: not shared between different browser Windows, even the same page; LocalStorage: shared in all origin Windows;
    • Cookie: Is also shared among all same-origin Windows.

HTTP status code:

  • 1XX (temporary response) : Status code that represents a temporary response and requires the requester to continue performing the operation.
    • 100(Continue) The requester should continue to make the request. The server returns this code to indicate that it has received the first part of the request and is waiting for the rest.
    • 101(Switching protocol) The requester has asked the server to switch protocol, and the server has confirmed and is ready to switch.

  

  • 2xx (success) : Indicates that the request status code is successfully processed.

    • 200(Success) The server has successfully processed the request. Typically, this means that the server has provided the requested web page. If this status code is displayed for your robots.txt file, it indicates that Googlebot successfully retrieved the file.
    • 201(Created) The request succeeded and the server created a new resource.
    • 202(Accepted) The server has accepted the request but has not yet processed it.
    • 203(Unauthorized Information) The server has successfully processed the request, but the information returned may come from another source.
    • 204(No content) The server successfully processed the request, but did not return any content.
    • 205(Reset Content) The server successfully processed the request, but did not return any content. Unlike the 204 response, this response requires the requester to reset the document view (for example, to clear the form content to enter new content).
    • 206 the server successfully processed some OF the GET requests.
  • 3XX (Redirection) : Further action is required to complete the request. Typically, these status codes are used for redirection.

    • 300(Multiple options) The server can perform a variety of operations on a request. The server can select an operation based on the requester (User Agent) or provide a list of operations for the requester to select.
    • The page for request 301(Permanent move) has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location. You should use this code to tell Googlebot that a web page or site has been permanently moved to a new location.
    • The 302(temporary mobile) server currently responds to requests from web pages in different locations, but requesters should continue to use the original location to respond to future requests. This code is similar to the 301 code that responds to GET and HEAD requests and automatically redirects the requester to a different location, but you should not use this code to tell Googlebot that a web page or site has moved, because Googlebot continues to crawl and index the original location.
    • 303(View other locations) The server returns this code when the requester should use a separate GET request for a different location to retrieve the response. For all requests other than HEAD, the server automatically redirects to another location.
    • 304(Unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. If the web page has not changed Since the requester last requested it, you should configure the server to return this response (called the if-Modified-since HTTP header). The server can tell Googlebot that the page hasn’t changed since it last crawled, saving bandwidth and overhead.
    • 305(Using a proxy) The requester can only access the requested web page using a proxy. If the server returns this response, it also indicates that the requester should use a proxy.
    • 307(temporary redirection) The server currently responds to requests from web pages in different locations, but the requester should continue to use the original location to respond to future requests. This code is similar to the 301 code that responds to GET and HEAD requests and automatically redirects the requester to a different location, but you should not use this code to tell Googlebot that a page or website has moved, because Googlebot continues to crawl and index the original location.
  • 4XX (Request error) : These status codes indicate that the request may be in error, preventing the server from processing it.

    • 400(Error request) Server does not understand the syntax of the request.
    • The 401(unauthorized) request requires authentication. The server may return this response for a web page requested after login.
    • 403(Forbidden) The server rejects the request. If you see this status code when Googlebot attempts to crawl a valid page on your site (you can see this information on a Web crawl page diagnosed by Google Webmaster Tools), your server or host may have denied Googlebot access.
    • 404(Not found) The server could not find the requested page. For example, this code is often returned for web pages that do not exist on the server.
    • 405(method disable) Disables the method specified in the request.
    • 406(Not accepted) Web pages that cannot respond to a request using the requested content feature.
    • 407(Proxy authorization required) This status code is similar to 401(unauthorized), but specifies that the requester should authorize the use of the proxy. If the server returns this response, it also indicates that the requester should use a proxy.
    • 408(Request Timeout) The server timed out while waiting for a request.
  • 5XX (server errors) : These status codes indicate that the server has an internal error while processing the request. These errors may be server errors rather than request errors.

    • 500(Server internal error) The server encountered an error and could not complete the request.
    • The 501(not yet implemented) server does not have the capability to complete requests. For example, the server may return this code if it does not recognize the request method.
    • 502(Error Gateway) server, acting as gateway or proxy, received invalid response from upstream server.
    • 503(Service unavailable) The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state.
    • 504(Gateway Timeout) The server acted as a gateway or proxy, but did not receive the request from the upstream server in time.
    • 505(HTTP version not supported) The server does not support the HTTP protocol version used in the request.

Front-end optimization methods:

Methods classification:

  • Reduce request volume: Merge resources, reduce HTTP requests, Minify/gzip compression,

WebPlazyLoad.

  • Speed up the request: pre-resolving DNS, reducing the number of domain names, parallel loading, CDN distribution.
  • Cache: HTTP protocol cache request, offline cache manifest, offline data cache localStorage.
  • Rendering: JS/CSS optimization, loading order, server-side rendering, pipeline.

Specific measures:

  1. Reduce the number of HTTP requests: CSS Sprites, JS, CSS source compression, image size control appropriate; Web Gzip, CDN hosting, data cache, picture server
  2. Front-end template JS+ data, reduce bandwidth waste caused by HTML tags, front-end variables to save AJAX request results, each operation of local variables, no request, reduce the number of requests
  3. Use innerHTML instead of DOM operations to reduce DOM operations and optimize JavaScript performance.
  4. When there are many styles to set, set className instead of manipulating Style directly
  5. Use fewer global variables and cache the results of DOM node lookups. Reduce I/O reads
  6. Avoid CSS Expression also known as Dynamic properties
  7. Image preloading, style sheet at top, script at bottom, time stamp.
  8. Prevent memory leaks: Memory leaks are the continued existence of any object after it is no longer owned or needed. The garbage collector periodically scans objects and counts the number of other references to each object. If the number of references to an object is zero (no other object references the object), or the only references to the object are cyclic, then the object’s memory is reclaimed.

Graceful degradation and progressive enhancement:

Progressively enhance the whole process from browser input url to page rendering: from the beginning, build the page for the lower version browser, complete the basic function, and then for the advanced browser effect, interaction, add functions to achieve a better experience. Graceful downgrading: Start by building the full functionality of the site, then test and fix it for browsers, such as building an application with CSS3 features, and then gradually hack it to work on older browsers.

Post and GET:

  • The GET parameter is passed through the URL, and the POST parameter is placed in the request body.
  • Get requests pass parameters in the URL with length limits, whereas POST does not.
  • Get is less secure than POST because parameters are directly exposed in the URL and therefore cannot be used to pass sensitive information.
  • Get requests can only be url encoded, while POST supports multiple encoding methods
  • Get request parameters are retained in the browser history, while POST parameters are not.
  • GET and POST are essentially TCP links and are no different. However, due to HTTP regulations and browser/server restrictions, they are applied differently.
  • GET generates a TCP packet; POST generates two TCP packets. For GET requests, the browser sends both HTTP headers and data, and the server responds with 200 (return data). For POST, the browser sends a header, the server responds with 100 continue, the browser sends data, and the server responds with 200 OK (returns data).

What is the difference between HTTP and HTTPS?

(1) HTTPS requires ca to apply for a certificate, which is usually less free. (2) HTTP is a hypertext transfer protocol, and information is transmitted in plain text, while HTTPS is a secure SSL encryption transfer protocol. (3) HTTP and HTTPS use completely different connection modes and different ports. The latter is 443 (4). HTTP connections are simple and stateless. HTTPS is a network protocol built by SSL + HTTP for encrypted transmission and identity authentication, which is safer than HTTP

The processing flow of HTTP cache is as follows:

There are two types of caching: strong caching and negotiated caching, depending on the header content of the response.

  • Strong caching is controlled using the Expires and cache-Control fields in the HTTP header to indicate the cache time of a resource. In a strong cache, a normal refresh ignores it, but does not clear it, requiring a forcible refresh. The browser forces a refresh with cache-control :no-cache and pragma: no-cache
  • Negotiation cache is the server to determine whether the cache resource is available, so the client and server must communicate through some kind of identifier, so that the server can determine whether the requested resource is cache accessible.
  • A normal refresh enables weak caching and ignores strong caching. Strong caching is enabled only when a url is entered in the address bar or favorites, a resource is referenced through a link, etc. This is why sometimes when we update an image or a JS file, the page content is still old, but when the direct browser accesses that image or file, the content is new. This mainly involves two sets of header fields related to the negotiated cache :Etag and if-none-match, last-Modified and if-Modified-since.

The browser cache process:

When a browser requests a resource, it obtains the header information of the resource cache and determines whether the resource Expires based on the cache-control and Expires information in the header.

  1. If not, the resource information is fetched directly from the cache, including cached headers, so the request does not communicate with the server. In this case, expiration is determined, which is strong cache correlation.
  2. If the display is expired, the browser sends a request to the server with the header field information about the cache returned by the first request.

For example, If the client sends an Etag to the server using the if-none-match header, the server will compare the Etag sent from the client to the server. If the Etag is the same, the server will set if-none-match to false and return status 304. The client continues to use the local cache and does not parse the data returned from the server. If the data is different, the client sets if-none-match to true and the status is 200. The client repeats the data returned from the server. The client will through the If – Modified – since previous server hair come over last Modified timestamp sent to the server, the server through the timestamp to determine whether the client page updated, If not the latest, it returns the latest content, If it is the latest, it returns 304, the client continues to use the local cache.

How to solve the caching problem in front-end development

  1. For developers, simply turn off the browser cache, find the Network, Disable cache option, and check to Disable the cache.
  2. You can turn caching off, but you can’t require all users to do this. You can concatenate random numbers or dates after referenced files, as in CSS /index.css? V =0.0001, the browser will assume it is a new request and will not use the cached file. Because each resource change updates the location of the reference and changes the value of the parameter, it is not very easy to operate, except in dynamic pages such as JSP with server variables (v=${sysRnd}).
  3. If a caching problem occurs in an Ajax request, a random number is appended to the address of the Ajax request
  4. CTRL + F5, this method can solve the page directly referenced resource update problem
  5. Develop using the browser’s privacy mode;
  6. If the page referenced by the resource is embedded in an iframe, you can right-click in the iframe area to reload the page

How html5 updates cached files (JS, CSS or images) in a timely manner

  1. Back-end interface Settings
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
Copy the code
  1. < meta http-equiv=” parameter “content=” parameter value” > < meta http-equiv=” parameter value “>
<meta http-equiv="Cache-Control" content="no-cache"> <meta http-equiv="Pragma" <meta http-equiv="Expires" content="0"> <meta http-equiv="Expires" content="0">Copy the code
  1. For images or CSS files, you can add a random number or flag bit to the end of the file name, for example
<link rel="stylesheet" href="./style/style.css? +Math.random()">Copy the code
  1. You can also take the 3 method for JS files, or use a timestamp after the file name
<script language="javascript" src="UILib/Common/Common.js? time=new Date()">Copy the code

Enter what happens after the URL arrives:

Simple process:

  1. DNS domain name resolution;
  2. Establish a TCP connection.
  3. Send an HTTP request;
  4. The server handles requests;
  5. Return the response result;
  6. Disable the TCP connection.
  7. Browsers parse HTML;
  8. Browser layout rendering;

Break down the process of building a request:

  1. The application layer performs DNS resolution

The DOMAIN name is resolved into an IP address through the DNS. During the resolution process, the cache is read in the sequence of browser cache, system cache, router cache, ISP DNS cache, root DNS server, top-level DNS server, and primary DNS server until the IP address is obtained. DNS pre-resolution is used to resolve the domain names that may be used later according to the rules defined by the browser, so that the resolution results are cached in the system cache, shortening the DNS resolution time, and improving the access speed of websites. 2. The application layer generates HTTP request packets. The application layer generates HTTP request packets for the target server, including the start line, header, and body. Header includes domain name host, keep-alive, user-agent, accept-endoding, accept-language, cookie, etc. 3. TCP protocol used by HTTP to establish TCP connections at the transport layer. The HTTP request packet is divided into multiple packet segments according to the sequence number, and each packet segment is encapsulated. The local random TCP source port is used to establish a connection to the tcp80 port (HTTPS is port 443) of the target server. The SOURCE and destination TCP ports are added to the packet. The protocol data unit, along with sequence number, confirmation number, validation and other parameters, adds a total of 20 bytes of header information. Setting up TCP connection requests here adds significant network latency. Common optimizations are as follows: 1) bundle resources to merge requests 2) use more caching to reduce network traffic 3) use keep-alive to establish persistent connections 4) Use multiple domain names to increase the number of concurrent browser resource loads, or use http2 pipelining connection multiplexing 4. The network layer uses the IP protocol to select routes. Process data segment from transport layer, load data segment into packet, fill packet header, add source and destination IP address, and then send data. The IP protocol is responsible for selecting the route of transmission, called the routing function. 5. Data link layer realizes reliable data communication between network neighboring nodes. In order to ensure data reliability, packet is encapsulated into frames and each frame is transmitted sequentially. CRC(cyclic redundancy test) is calculated for each data block to prevent packet loss and retransmission if errors occur. The packet is encapsulated into frames, which are divided into frame header and frame tail. The frame tail is the CRC check part. The frame header is to add the address of the data link layer, source address and destination address, namely the MAC address between the adjacent nodes of the network. Transmission data at the physical layer Converts frames at the data link layer into bitstreams in binary form, which are sent from the network card and then converted into electronic and optical signals for transmission over the network.

Summary: The six steps are as follows: DNS parses URL addresses, generates HTTP request packets, constructs TCP links, selects transmission routes using IP protocols, ensures reliable data transmission at the data link layer, and converts data to physical signals for transmission at the physical layer.

Supplementary: Server processing and reverse transmission: The server receives the bit stream, converts the bit stream into a frame format, and uplots the packet to the data link layer. The server finds that the destination MAC address in the data frame is the same as the MAC address of the network card. The server unwraps the packet from the data link layer and uplots the packet to the network layer. The network layer of the server compares the destination IP address in the data packet and finds that the destination IP address is the same as the local IP address. The server unwraps the network IP address and uploads the data to the transport layer. The transmission layer confirms, sorts and reorganizes data segments to ensure the reliability of data transmission. Finally, the data is transmitted to the application layer of the server. Then, through layer upon layer encapsulation of transmission layer, network layer and data link layer, the response message is finally encapsulated into binary bit stream and converted into other signals, such as electrical signals transmitted to the network. The process of reverse transmission is similar to that of forward transmission

The browser rendering process:

The main steps

  1. The browser parses the retrieved HTML document into a DOM tree
  2. Processing CSS markup to form the Cascading style sheet model CSSOM (CSS Object Model)
  3. Combine DOM and CSSOM into a rendering tree, representing a set of rendering objects
  4. Each element of the rendering tree contains a calculated content, called a layout layout, and the browser uses a streaming approach that lays out all elements in a single drawing operation
  5. Drawing the nodes of the render tree onto the screen is called painting

Specific process:

Build a DOM tree:

When the browser receives the HTML document from the server, it iterates through the document nodes to generate a DOM tree, which may be blocked by CSS and JS loading. Display: None elements, comments, and scripts also exist in the DOM tree.

Build the CSSOM rule tree

The browser parses the CSS file and generates a stylesheet object for each file, each of which contains the CSS rules. CSS parsing can be done at the same time as DOM parsing, and CSS parsing is mutually exclusive with JS.

Build the render tree:

The browser traverses each visible node from the root of the DOM tree, then finds the CSS style rules for each visible node and applies them. The display: None element is not in the Render tree, and the visibility:hidden element is in the Render tree. This time has not been rendered to the screen, rendering to the screen needs to use the location information of each node, need to deal with the layout

Render tree Layout:

Layout stage, traverse each Render Object, including width, height, position, background color and other style information, through these information to determine the exact position of each node on the page. Out of the document flow, out of the Render Tree

Render Tree paint:

In the draw phase, the browser traverses the render tree and calls the renderer’s paint() method to display its content on the screen, which is done by the browser’s back-end UI.

Js blocking: Js can manipulate the DOM to change the STRUCTURE of the DOM and modify the CSSOM style, so when the browser encounters a

Layout and repaint:

DOM changes affect rendered geometry, such as width and height. The browser recalculates the geometry of the element, and the geometry of other elements is also affected. The browser needs to reconstruct the Render tree, a process called reflow. The process by which the browser redraws the affected parts on the screen is called redrawing. Display: None triggers reflow, while visibility: Hidden is not invisible and only triggers repaint

The reasons for redrawing are as follows:

  • Add or remove visible DOM elements,
  • The size position of the element changes.
  • The browser page is initialized
  • The browser window size changed. Procedure
  • Rearrangement does not necessarily lead to redrawing, and redrawing does not necessarily lead to rearrangement.

Ways to reduce redraw rearrangements:

  • Don’t do DOM queries when layout information changes
  • Instead of changing the DOM style one by one, use csSText, className to change the property once
  • Manipulate the node in memory several times before adding it to the document
  • When a complex operation is performed on an element, hide it and then show it
  • Cache in variables when you need to frequently retrieve properties that cause browser rearrangements
  • Do not use the table layout, a small change will cause the table to be rearranged
  • For elements that are rearranged multiple times, such as animations, use absolute positioning to keep them out of the document flow so that they do not affect other elements and reduce the scope for redrawing

HTTP packets consist of:

What are the advantages of using HTTP long connections?

HTTP persistent connection: Sending multiple HTTP requests and receiving multiple HTTP responses on top of a TCP connection, in order to avoid opening a new connection with each request. Short connections are used by default in HTTP/1.0. That is, each time the client and server perform an HTTP operation, a connection is established and broken at the end of the task. From HTTP/1.1 onwards, long connections are used by default to preserve the connection feature. HTTP with long connections adds this line to the response header: Connection:keep-alive When a long Connection is used, after a web page is opened, the TCP Connection used to transmit HTTP data between the client and the server is not closed. When the client accesses the server again, the existing Connection is used. Keep-alive does not hold a connection forever, it has a hold time that can be set in different server software such as Apache. To implement persistent connections, both clients and servers must support persistent connections. HTTP long connection and short connection are essentially TCP long connection and short connection.

Long connection features:

This saves more TCP connection establishment and closing operations, reducing waste and saving time. It is suitable for establishing between clients that frequently request server resources.

Short connection features:

For the server, it is easy to manage and the existing connections are all useful connections. However, if the client requests frequently, it wastes time and bandwidth in establishing and closing TCP operations. The HTTP service of WEB site generally adopts short connection service.

If the connection between the client and the server is not closed, the pressure on the server increases as more and more clients establish connections. Therefore, the following measures are generally adopted: 1. Close some connections that have not had a read or write event for a long time. 2. Limit the maximum number of persistent connections on each client.

The TLS/SSL protocol ensures information security:

SSL(Secure Socket Protocol) is a protocol for the secure exchange of information between Web browsers and Web servers. It provides two basic security services, authentication and confidentiality. TLS(Secure Transport Layer Protocol) is used to provide confidentiality and data integrity between two communication applications. TLS is an upgraded version of SSL

Basic process of SSL/TLS protocol

(1) The client requests and verifies the public key from the server. (2) Both parties negotiate to generate the “dialogue key”. (3) Both parties use the “dialogue key” for encrypted communication. The process can be broken down into 8 steps:

  1. The client makes an HTTPS request to the server and connects to port 443 of the server
  2. The server has key pairs, public and private keys, for asymmetric encryption
  3. The server sends the public key to the client
  4. After receiving the data from the server, the client verifies the validity of the certificate. If the certificate is valid, the client generates a client key and encrypts the key using the public key received from the server.
  5. The client initiates an HTTPS request again and sends the encrypted client key to the server
  6. The server receives the encrypted key sent by the client, decrypts the data with its own private key, and encrypts the data with the client key.
  7. Sends encrypted data to the client
  8. The client uses the client key to decrypt the encrypted data and obtain the data sent by the server.

Contents of the SSL protocol:

  • Handshake protocol

Handshake protocol is the client and the server SSL connection communication is used when the first child of the agreement, the handshake protocol includes a series of messages between client and server, SSL protocol is one of the most complex agreement, the agreement allows the server and client authentication, each other to negotiate encryption algorithm and MAC (with secret key Hash function) and the secret key, Used to protect data sent in SSL records, the handshake protocol is used prior to the application’s data transfer. 1.1 Establish security capability, send information, exchange version, random number, session ID, password suite, compression method and other information 1.2 Server authentication and key exchange 1.3 Client authentication and key exchange 1.4 complete

  • Record deal

The recording protocol is used after the client and server successfully shake hands, that is, after the client and server identify each other and determine the algorithm to use for the secure information exchange, the SSL recording protocol is entered.

  • Alarm agreement

When the client and server discover an error, they send an alert message to each other. If the error is fatal, the algorithm immediately closes the SSL connection and both parties delete the relevant session number, key, and so on.

Summary: In SSL, the handshake protocol is used to negotiate encryption and MAC algorithms and secret keys, the handshake protocol is used to encrypt and sign exchanged data, and the alarm protocol is used to define how to solve problems in the process of data transmission.

HTTP 1.0,1.1,2.0 protocol differences:

HTTP1.0 requires the keep-alive parameter to tell the server to establish a long connection. HTTP1.1 supports long connections by default. HTTP is based on THE TCP/IP protocol. Creating a TCP connection requires a three-way handshake, which costs a certain amount of money. If a connection needs to be re-established each time, performance will be affected. Therefore, it is best to maintain a long connection, which can be used to send multiple requests. Bandwidth Saving HTTP 1.1 supports sending only header information (without any body information), 100 if the server thinks the client has permission to request the server, 401 otherwise. The client does not start sending the request body to the server until it receives 100. This saves bandwidth by saving the client from sending the body request when the server returns 401. HTTP also supports sending portions of content. In this way, when the client already has some resources, it only needs to request other resources from the server. This is the basis for supporting file breakpoint continuation. HOST domains are now available to Web Servers such as Tomat, and it is very common to set up virtual sites, that is, multiple virtual sites on a Web Server can share the same IP address and port. HTTP1.0 does not have a host field; HTTP1.1 only supports this parameter.

HTTP2.0 uses an epoll multiplexing technique to concurrently process multiple requests for the same connection, and the number of concurrent requests is several orders of magnitude larger than HTTP1.1. Of course, HTTP1.1 can also establish several more TCP connections to support handling more concurrent requests, but creating TCP connections is inherently expensive. TCP connections are preheated and protected by checking whether data is successfully transmitted. If yes, the transmission speed is increased. Therefore, for instantaneous concurrent connections, the server responds slowly. It is best to use an established connection that can support instantaneous concurrent requests. Data compression HTTP1.1 does not support header data compression, HTTP2.0 uses the HPACK algorithm for header data compression, so that the data volume is small, over the network transmission will be faster. The definition of the request and response headers is essentially unchanged in HTTP2.0, except that all header keys must be lowercase and the lines must be independent of :method:, :scheme:, :host:, : PATH:. These key-value pairs are no longer sent through each request and response for the same data. Each new header key-value pair either appends to the end of the current table or replaces the previous value in the table. The header table exists throughout the lifetime of the HTTP2.0 link and is gradually updated by both the client and the server. Server push means that when we request data from a Web server that supports HTTP2.0, the server will incidentally push some resources that the client needs to the client, so that the client will not create a connection to send the request to the server. This is a great way to load static resources. These resources pushed by the server side actually exist somewhere on the client side, and the client side can load these resources directly from the local, without going to the network, the speed is naturally much faster. Binary frame layer HTTP2.0 breaks all information into smaller messages and frames and encapsulates them in binary format. For example, header encapsulates a Headers frame and Request Body encapsulates a Data frame. HTTP2.0 communication is all done over a TCP connection that can host any number of two-way data streams, each of which is sent as a message. A message consists of one or more frames, which can be sent out of order and then reassembled according to the stream identifier at the beginning of each frame.

The WebSocket protocol:

Ajax polling ajax (asynchronous javascript and XML technology) is an asynchronous communication method that effectively leverages javascript and DOM operations to enable local Web pages to be texted and loaded. Compared with the previous synchronous communication, it only updates a part of the page, so the amount of data transferred will be reduced accordingly.

Ajax polling works by having the browser send a request every once in a while to ask the server if there is a new message. Getting content from the server in real time with Ajax can lead to a lot of requests.

The principle of long polling is similar to that of Ajax polling in that it takes the form of polling but uses the blocking model. That is, when the client initiates a connection, if the server does not update the content, the response will be suspended, and the client does not reply to the response until the content is updated, and then returns the response.

  • HTTP features: passive, requests can only be initiated by the client. The server cannot proactively contact the client.
  • Ajax polling requires fast processing speed and resources on the server. (speed)
  • Long polling requires high concurrency, that is, the ability to receive customers at the same time. (Site size)

WebSocket

  • WebSocket is the HTML5 thing (protocol), IS HTML5 began to provide a browser and server for full duplex communication network technology, belongs to the application layer protocol. It is based on the TCP transport protocol and reuses the HTTP handshake channel.
  • Once the WebSocket protocol communication connection is established between the Web server and the client, all subsequent communication relies on this dedicated connection. An endless stream of information can be sent through a single HTTP request.
  • By setting it in the request headerConnection: UpgradeTo use the WebSocket protocol

The WebSocket protocol has the following features push the server to the client. The server can send data directly without waiting for requests from the client. Reduce traffic Once a WebSocket connection is established, it remains connected, and messages can be sent continuously until the request is closed. This avoids the statelessness of HTTP. Compared with HTTP, not only the total cost of each connection is reduced, but also the header information of Websocket is small and the traffic is reduced. Support two-way communication, more real-time. Better binary support. Less control overhead. After the connection is created, when the WS client and server exchange data, the packet header controlled by the protocol is small. Without the header, the client-to-client header is only 2 to 10 bytes (depending on the packet length), with an additional 4-byte mask for client-to-server. HTTP requires a complete header for each communication. Support for extensions The WS protocol defines extensions that users can extend or implement custom subprotocols. (such as support for custom compression algorithms)

The CSS part:

CSS 3 feature:

CSS3 border such as border-radius, box-shadow, etc. CSS3 background such as background-size, background-origin, etc. CSS3 2D, 3D conversion such as transform; CSS3 animation, such as animation. New features of CSS3 include flex layout, first-of-type, NTH-Child and other selectors, box-sizing to change box models, animation, 2D transform, 3D transform, etc. Add transparency in color, RBGA, etc., allow font embedding and font shading in font, and finally, media search etc.

Two box models of CSS

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

If you want to switch box models easily, you need to use cSS3’s box-sizing property

Box-sizing: Content-box is a W3C box model

Box-sizing: border-box is IE box model

The default property for box-sizing is content-box

Vertical center:

  • Use positioning and negative margins, parent element, child element fixed width and height, parent element, child element top attribute 50%, margin margin-top is half of the child element’s own height (this method requires knowing the height of the child element)
  • Using position and transform, parent element fixed width and height, parent phase, child element top attribute 50%, the transform attribute is Y axis offset -50%
  • Use positioning automatic margin, parent element, child element fixed width and height, parent element, child element top, bottom attribute 0,margin in vertical direction auto
  • Using Flex layout, parent element, child element fixed width and height, parent element using Flex layout, set align-items property to Center
  • With flex layout, the parent element, the child element, and the parent element use Flex layout, set the flex-direction property to Column and the justify-content property to center
  • Run display:table-cell, the parent element fixes the width and height, the parent element sets display:table, the child element sets display:table-cell, and vertical-align:middle

The difference between Transition and animation

Animation and Transition have most of the same properties. They both change the value of an element’s properties over time. The main difference is that Transition needs to trigger an event to change its properties, while animation does not need to trigger any events to change its properties over time. And transition to 2 frames, from…. To, and animation can do it frame by frame.

Animation attributes

  • Name Sets the name of the animation,
  • Duration Sets the period during which the animation is completed,
  • Timing-function Sets the speed curve of the animation,
  • Delay sets when the animation starts,
  • Rotund-count sets the number of times the animation is played,
  • Direction Specifies whether the next cycle is played in reverse.
  • Whether the play-state animation is in progress or paused,
  • Fill-mode sets the state of the position after the animation stops

The transition properties

  • Property to set the transition effect’s property name,
  • Duration Specifies the duration of the transition effect,
  • Timing -function Specifies the speed curve of the speed effect,
  • Delay sets when the transition effect starts.

The difference between:

  1. Transition is a process of changing style values, only a beginning and an end. Animation is also called keyframe. By combining with @keyFrame, you can set one state of the intermediate frame.
  2. Animation and @KeyFrame can trigger this process without triggering an event, while Transition needs to trigger an hover or JS event.
  3. The animation can set many properties, such as the number of cycles, the state at the end of the animation, and so on.
  4. Animation can set each frame with the KeyFrame, but Transition only has two frames.
  5. In terms of performance: the browser has a main thread and a layout thread; The main thread is generally running on JS, page layout, bitmap generation, and so on, and then the generated good bitmap to the layout thread, and the layout thread will draw the bitmap to the page through THE GPU, will also request the bitmap to the main thread, and so on; When we use animation, we can change many properties, such as width, height, position and so on. When we change the properties of document flow, page backflow and redraw will be caused, which will have a great impact on performance. But when we use transition, we use transform to rotate and scale and so on, and we don’t create new bitmaps, and we don’t rearrange pages;

Transition, Transform and Translate

Transform is a transform that changes the appearance of the element. There are many ways to change the appearance, such as displacement, scaling, rotation, etc. The name of the transform function is translate, so translate is part of transform. Transform: [transform function]; Rotate (Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : rotate(Angle) : Element rotation, rotation Angle, unit deg, clockwise rotation

transform: translate(-10px, 10px); // Move the current element 10 pixels up and 10 pixels to the right. transform: translate(10px, 10px) rotate(10deg); // Specify multiple conversion effects.Copy the code

Transition refers to how smoothly the value of a CSS property changes. The transform has no animation. You change its value, and the element looks different.

Transition: [attribute name] [duration] [speed curve] [delay time]; transition: height 2s ease .5s; // When the value of the height property changes, the ease curve transitions with a delay of 0.5 seconds for 2 seconds.Copy the code

Opacity =hidden, opacity=0, display:none:

  • Opacity =0, this element is hidden but does not change the page layout, and if the element is already bound to events, such as click events, clicking on this area can also trigger the click event method.
  • Visibility =hidden, the element is hidden, but does not change the page layout, but does not trigger events that the element is already bound to.
  • Display = None, which hides the element and changes the page layout, can be interpreted as removing the element from the page.

Comparison of position attributes:

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

If an element is positioned relative to its original position, 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, the element still occupies the original space, whether or not it is moved. Therefore, moving an element causes it to overwrite other boxes.

Absolute: Moves an absolutely positioned element relative to its parent element relative to the nearest positioned parent element or, if the element has no positioned parent element, relative to < HTML >. 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 positioning: it moves relative to its original position, and then, when it exceeds the target area, it is fixed in the target position, that is, it is positioned according to relative and then fix positioning. The element is positioned according to the normal document flow and then relative to the element’s flow root (BFC) and containing block (the nearest block-level ancestor element) in the flow. Element positioning is then expressed as 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 declarations).

Inherit: Specifies that the value of the Position property should be inherited from the parent element.

Several methods of floating cleanup:

use an empty element after the float element. } property cleans up the float. Alternatively, use

or


.

Method 2: Add overflow: Hidden to the floating element container using the OVERFLOW property of CSS. Or overflow: auto; You can clear floats, and in IE6 you also need to trigger hasLayout, such as setting the container width or zoom:1 for the parent element. After the overflow property is added, the float element goes back to the container layer and pushes up the container height to clean up the float.

Method 3: Add float to the container of floating elements add float attribute to the container of floating elements to clear the internal float, but this will make the whole float, affect the layout, not recommended.

Method 4: Do nothing with the adjacency element and add the clear attribute to the element after the float element.

Method five: use CSS :after pseudo-element combination :after pseudo-element (note that this is not a pseudo-class, but a pseudo-element, after the most recent element) and IEhack, can be perfectly compatible with the current mainstream of each major browser, here IEhack refers to trigger hasLayout. Add a ClearFix class to the container of floating elements, and then add one to the class :after pseudo-element implementation adds an invisible Block element to the end of the element to clean up the float.

What are the CSS selectors and their priorities?

There are four basic selectors and four advanced selectors for CSS:

Basic selector:

Tag selector: for a class of tag P{} : selects all < P > elements

ID selector: For a particular tag use # ID {} : select all elements with ID =” firstName”

Class selector: For all tags you want, use.class{} : select all class=”intro” elements

Universal selector (wildcard) : Applies to all labels (not recommended)

  • : Selects all elements

Advanced selector:

Div >p: Selects all

elements within the

element whose parent is

element. Div + P: selects all

elements immediately following the

element

[target] : selects all elements with the target attribute [target=-blank] : selects all elements with target=”-blank” [title~=flower] : Choose title attribute contains the word “flower” all the elements of [lang | = en] : choose the lang attribute en as at the beginning of all elements

Intersection selector: used. Separate h3.special: Select the

tag and the tag whose class is. Special

Union selectors (grouping selectors) : separate div elements with commas,p: select all

elements and

elements P,h1,#mytitle,. One: Select all tags with P,h1, ID =”mytitle”,class=”one”

Pseudo-class selector: static pseudo-class selector: A :link: select all unvisited links A :visited: Select all visited links dynamic pseudo-class selector: A :active: select active links A :hover: select input:focus: Select input element order pseudo-class selector with focus: P :first-letter: selects the first letter of each P element P :first-line: selects the first line of each P element P :first-child: specifies the style only if the P element is the first child of its parent. P :before: inserts content before each p element p: After: inserts content after each P element

Css3 new selector: p~ul: select each ul element a[SRC ^” TTPS “] : select each element a[SRC $=”.pdf “] with SRC attribute value starting with “HTTPS” : [SRC *=” runoob”] : Select the value of each SRC attribute containing the substring “‘runoob” element P :first-of-type: Select the first p element where each p element is its parent p:last-of-type: select the last p element where each P element is its parent p:only-of-type: select the only p element where each P element is its parent p:only-child: P :nth-child(2) : select the second child of each p element that is its parent p::nth-child(-n+3): select the first three children of each P element that is its parent P :th-last-child(2) : Each p element selects the second child of its parent, counting from the last child p:th-of-type(2) : selects the second p element of each p element that is its parent p:nth-last-of-type(2) : Each p element is selected as the second p element of its parent, counting from the last child p:last-child: Each P element is selected as the last-child of its parent. .root: selects the root element of the document. P :empty: selects every P element without any children (including text nodes). #news:target: selects the current active #news element (containing the clicked URL of the anchor name). Input. checked: Selects each selected input element: Not (p) : Selects each element that is not a P element: Selection: Out-of-range: matching input elements with matching values outside the specified range :in-range: matching input elements with matching values within the specified range. Read-write: matching readable and writable elements :read-only: Used to match elements with the “readonly” attribute set :optional: Used to match optional input elements. Required: Used to match elements with the “required” attribute set valid: Used to match elements with an input value of the “standard” cinVALID: Matches elements whose input value is illegal

Css selector priority:

  1. Use after properties! Important overrides element styles defined anywhere in the page.
  2. The style written inside the element as the style attribute
  3. The id selector
  4. Class selectors
  5. Element selector
  6. Wildcard selector
  7. Browser customization or inheritance

Margin collapse and merge problems:

Firstly, margin collapse is two elements relative to parent-child relationship, while margin merge is two elements relative to two sibling relationship

The margins of two sibling elements, the vertical margin, will overlap. The margins of the two elements are the maximum values of the two set margins, which is the margin combination problem

The vertical margin of the two parent-child relationship elements will be glued together, the outer and model margin-top take the maximum margin-top of the two elements, the inner element where margin collapse occurs relative to the whole document move solution: both can be solved by triggering BFC

What is BFC:

A block-level formatting context is a separate rendering area with certain layout rules.

  • The BFC area does not overlap with the float box.
  • The BFC is a separate container on the page, and the child elements do not affect the outside.
  • When calculating the height of the BFC, floating elements are also involved in the calculation.
  • And in a BFC, block boxes and row boxes (which consist of all inline elements in a row) are arranged vertically along the border of their parent element.

Which elements generate the BFC:

  • Float is an element that is not None
  • Position is an element of fixed and absolute
  • Display inline-block, table-cell, table-caption, flex, inline-flex element
  • Overflow is not a visible element

The difference between inline-block, inline and block:

  • A Block is a block-level element that has line breaks before and after it, and can set width, height, and margin/padding in both horizontal and vertical directions.
  • Inline: Sets width and height to invalid, margin to invalid on vertical, padding to invalid on horizontal and vertical, and no line breaks before or after
  • Inline-block: the width and height can be set. Margin /padding is valid in both horizontal and vertical directions

Px, EM, REM, %, VW, VH, VM

  • Em: refers to the parent element’s font size, which is inherited from the parent element. If you define a font size for yourself (the default font is 16px), 1em is not a fixed value for the entire page
  • Rem: Relative to the root HTML, you can set the font size of the root HTML to 10px, so 1.2em is 12px;
  • Vw :css3 new unit, short for view width, refers to the height of the visible window, if the width is 1200px, then 10vw is 120px; For example: 1200px browser width, 1 vw = 1200px/100 = 12 px.
  • Vh: Similar to VW, refers to the height of the visible window.
  • Vm: the smallest unit relative to the width or height of the viewport is divided into 100 units, for example: browser height 900px, width 1200px, take the smallest browser height, 1 Vm = 900px/100 = 9 px.

Flex layout:

Common Flex properties:

  • Display: Specifies the HTML element box type.

  • Flex-direction: specifies the arrangement of neutrons in an elastic container

    • Row: Horizontal alignment from left to right (left-aligned), default alignment.
    • Row-reverse: horizontal alignment (right-aligned, from back to front, with the last item at the top.
    • Column: indicates the vertical array.
    • Column-reverse: to reverse vertically, from back to front, with the last item at the top.
  • Context-content: Sets the alignment of elastic box elements along the main axis (horizontal axis).

    • Flex-start: Elastic items are filled right next to the wardrobe. This is the default. The main-start margin of the first elastic term is placed on the main-start margin of the line, and the subsequent elastic terms are placed flush.
    • Flex-end: The elastic item is populated right next to the end of the line. The main-end margin of the first elastic term is placed on the main-end edge of the row, and the subsequent elastic terms are placed flush.
    • Center: Elastic items center next to fill. If the remaining free space is negative, the elastic item will overflow in both directions at the same time.
    • Space-between: Elastic items are evenly distributed on the row. If the remaining space is negative or there is only one elastic term, this value is equivalent to flex-start. Otherwise, the margin of the first elastic term is aligned with the main-start line of the line, and the margin of the last elastic term is aligned with the main-end line of the line, and then the remaining elastic terms are distributed on the line with equal intervals between adjacent items.
    • Space-around: Elastic items are evenly distributed on a line with half of the space between them. If the remaining space is negative or there is only one elastic term, this value is equal to center. Otherwise, the elastic items are distributed along a row evenly spaced from each other (say 20px), with half of the space between the two sides and the elastic container (1/2 x 20px=10px).
  • Align-items: Sets the alignment of the elastic box elements along the side axis (vertical axis).

    • Flex-start: The boundary of the lateral (vertical) starting position of the elastic box element is close to the lateral starting boundary of the row.
    • Flex-end: The boundary of the start position of the side axis (vertical axis) of the elastic box element is immediately adjacent to the end boundary of the side axis of the row.
    • Center: The elastic box element is centered on the lateral axis (vertical axis) of the row. (If the size of the line is less than the size of the elastic box element, the same length + degree will overflow in both directions).
    • Baseline: Equivalent to ‘flex-start’ if the inner and side axes of an elastic box element are the same. In other cases, this value will participate in baseline alignment.
    • Stretch: If ‘auto’ is used to specify the size of the side axis, it will make the size of the project’s margin box as close to the size of the row as possible, but conform to the limits of the ‘min/max-width/height’ property.
  • Flex-wrap: Sets whether the children of the elastic box are wrapped when they exceed the parent container.

    • Nowrap – By default, elastic containers are single lines. In this case the elastic child may overflow the container.
    • Wrap – Elastic container for multiple lines. In this case, the overflow part of the elastic subitem will be placed in the new line, and line breaking will occur inside the subitem
    • Wrap-reverse – Reverses the wrap arrangement.
  • Align-content: Changes the behavior of the flex-wrap property, like align-items, but instead of setting the alignment of child elements, it sets the alignment of lines.

    • Stretch – Default. The rows will stretch out to take up the remaining space.
    • Flex-start – Stack each row to the starting position of the elastic box container.
    • Flex-end – Stack each line toward the end of the elastic box container.
    • Center – The rows are stacked in the middle of the elastic box container.
    • Space-between – The rows are evenly distributed in the elastic box container.
    • Space-around – The rows are evenly distributed in an elastic box container, with each end retaining half of the spacing between the child elements.
  • Flex-flow: short for flex-direction and flex-wrap

  • Order: Sets the order of the children of the elastic box.

    • Integer: Defines the sequence of integer values, with the smallest values in the first order. It can be negative.
  • Align-self: used on elastic child elements. Overrides the align-items property of the container.

    • Auto: If ‘align-self’ is ‘auto’, it evaluates to the ‘align-items’ value of the element’s parent, or ‘stretch’ if it has no parent.
    • Flex-start: The boundary of the lateral (vertical) starting position of the elastic box element is close to the lateral starting boundary of the row.
    • Flex-end: The boundary of the start position of the side axis (vertical axis) of the elastic box element is immediately adjacent to the end boundary of the side axis of the row.
    • Center: The elastic box element is centered on the lateral axis (vertical axis) of the row. (If the size of the line is smaller than the size of the elastic box element, the same length will overflow in both directions).
    • Baseline: Equivalent to ‘flex-start’ if the inner and side axes of an elastic box element are the same. In other cases, this value will participate in baseline alignment.
    • Stretch: If ‘auto’ is used to specify the size of the side axis, it will make the size of the project’s margin box as close to the size of the row as possible, but conform to the limits of the ‘min/max-width/height’ property.
  • Flex: Sets how the children of the elastic box allocate space.

    • Auto: The calculated value is 1. 1 Auto
    • Initial: The calculated value is 0. 1 Auto
    • None: The calculated value is 0. 0 Auto
    • Inherit: Inherit from the parent element
    • [flex-grow] : Defines the expansion ratio of the elastic box element.
    • [flex-shrink] : Defines the shrink rate of elastic box elements.
    • [flex-basis] : defines the default reference value for the elastic box element.

The difference between a streaming layout and a responsive layout:

Common Flex properties:

  • Streaming layout: Use non-fixed pixels to define web content, known as percentage layout, by setting the degree of the box as a percentage to scale according to the width of the screen, not limited by fixed pixels, content automatically fills.
  • Reactive layout, which uses Media Query in CSS3 to specify the layout of a web page with a width range by querying the width of the screen

Ultra small screen (mobile device):768px below small screen device: 768px-992px; Medium screen device: 992-1200px; Since responsive layout development is cumbersome, third-party responsive frameworks such as Bootstrap are generally used to complete part of the work

Implementation of the three-column layout:

Common Flex properties:

  1. floating

Set the height of the three columns, the width of the left and right columns is fixed, and set the left and right floating columns respectively. Advantages: Good compatibility Disadvantages: Floating out of the document flow, need to clear floating processing 2. Absolute positioning parent element set absolute positioning, left and right column fixed width, left column set left:0; The right column sets right:0; In the middle bar, set left and right as the width of the left and right columns respectively. Advantages: Fast, not prone to problems. Disadvantages: Display: Flex, left and right bar fixed width, middle bar set Flex :1, occupy the remaining space Advantages: Relatively perfect, mobile layout mostly belongs to Flex 4. Display :table-cell, fixed width of left and right columns Advantages: Good compatibility Disadvantages: Cumbersome operation. When the height of one cell increases, the height of other cells increases accordingly 5. Display :grid, fixed width, grid-template-rows: 100px; grid-template-columns: 300px auto 300px; Advantages: Can do a lot of complex things, the code is relatively simple Disadvantages: new technology, low browser compatibility

JS:

JS basic data types:

Simple data types: Undefined, Null, Boolean, Number and String. Es6xinzeng Complex data types: Object Basic data types are viewed through typeof, where Null returns Object, which is understood as an empty Object.

Null and undefined:

  • Null represents a nonexistent object, which translates to 0, an object that does not yet exist, and is often used when a function attempts to return a nonexistent object

Usage:

  1. As arguments to a function, indicating that the function’s arguments are not objects
  2. As the end of the object prototype chain
  • Undefined is a primitive value for nothing, converted to a value of NaN. The default value of the declared variable is Undefined when it is not initialized

Usage:

  1. A variable that is declared but not assigned is undefined
  2. When the function is called, the argument that should be provided is not provided, which is equal to undefined
  3. The object has no assignment property, which has a value of undefined
  4. If the function returns no value, undefined is returned by default

ES6 new

1. Add declaration commands let and const, let stands for variable, const stands for constant.

  • Let and const are both block-level scoped, with {} code blocks as scoped, and can only be used inside code blocks.
  • There is no variable promotion, only declare before use, otherwise an error is reported. A variable is not available until it is declared.
  • Duplicate declarations are not allowed within the same code block.
  • Const declares a read-only constant and is assigned when declared. (If const is an object, the value of the object can be modified, i.e. the address to which the object points cannot be changed, and member variables can be modified.)

2. Template string

Use a pair of backquotes as an identifier, can be used as a regular string, can be used to define a multi-line string, can also be embedded in the string variables, JS expressions or functions, variables, JS expressions or functions need to be written inThe ${}In the.

3. Function related extension method

The function’s default argument, ES6, provides a default value for the argument, which is initialized when the function is defined so that it can be used if the argument is not passed in. Arrow function name =(parameter)=>{…… }, {} and return can be omitted when there is only one expression in the function body, and () can be omitted when there is only one parameter in the function body. Features:

  • Arrow functions are anonymous and cannot be used as constructors. New cannot be used
  • Arrow functions do not bind arguments, use rest arguments… Instead of
  • The arrow function does not bind this and captures the this value of its context as its own this value
  • No method can change the orientation of this in arrow functions. Arrow functions that call a function through call() and apply() pass in arguments and do not change the orientation of this

Arrow functions have no stereotype attributes

  • Arrow functions should not be treated as Generator functions and the yield keyword should not be used

  • The difference between this and ordinary functions is that in ordinary functions, this always refers to the last object to which it was called (such as the function defined in the object, this inside the function refers to this object). If the object is not called directly, it will refer to undefined or window. Only in strict mode will it point to undefined.

There are four modes of calling this in ordinary functions:

  • Call mode functionally

If a function is not a property of an object, it is called as a function. This refers to the window

  • Method type call

When a function is stored as a property of an object, we call it a method. When a method is called, this is bound to the current object

  • Constructor – style call

If the function is called with the new keyword, this is bound to the created new object.

  • Context invocation (borrowing the method pattern)

The context call mode, also known as method borrowing mode, is divided into apply and call, using methods: function.call () or function.apply ()

  • Several special this Pointers

The this in the timer refers to the window because the function of the timer is ultimately called by the window. The this in the event refers to the current element, and when the event is triggered, the browser makes the current element call function

4. Object related extension methods

  • Short for property. ES6 allows variables to be written directly to objects. In this case, the property name is the variable name, and the property value is the value of the variable.

  • The object.keys () method gets all the property or method names of the Object (excluding the contents of the prototype) and returns an array.

  • Object.assign (). The assign method combines the attributes and methods of multiple original objects onto the target Object. You can take multiple arguments, the first being the target object, followed by the source object.

Deep copy of level-1 attributes, shallow copy of subsequent level-2 attributes

5. The for of circulation

Is a uniform way to traverse all data structures. for… The scope of the of loop includes arrays, Set and Map structures, some array-like objects (such as Arguments objects, DOM NodeList objects), Generator objects, and strings.Cannot iterate over an object because it has no built-in iterator

6. The import and export

  • JavaScript natively supports modules in the ES6 standard. This kind of JS code is divided into small blocks of different functions for modularization, the code of different functions are written in different files, each module only needs to export the public interface part, and then through the import of the module can be used in other places.
  • Export Interface for exporting variables of this module (a file can be understood as a module).
  • Import is used to load a module with another module that contains the export interface.
  • Import and export commands can only be at the top of a module, not in a code block.

7. Deconstruct assignments

  • ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called Destructuring.
  • Array deconstruction assignment, the value in the array will be automatically resolved to the corresponding variable to receive the value, the array deconstruction assignment must correspond to one by one if there is a mismatch is undefined

  • Object deconstruction assignment. Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value.

8. Set data structure

A Set data structure, similar to an array in that all data is unique and has no duplicate values, is itself a constructor property and method:

  • Size Indicates the data length
  • Add () adds a value and returns the Set structure itself.
  • Delete () deletes a value and returns a Boolean indicating whether the deletion was successful.
  • Has () looks for a piece of data and returns a Boolean value.
  • Clear () clears all members with no return value.
  • Application: array deduplication

  • You can use array. from(new Set(arr)) or […new Set(arr)] to return arrays.

9. Map data structure

The Map structure is a set of key-value pairs (Hash structure). The default object representation in JS is {}, that is, a set of key-value pairs, but the key must be a string. To use Number or other data types as keys, the ES6 specification introduces a new data type Map. A Map is a structure of key-value pairs with extremely fast lookup times. Initializing a Map requires either a two-dimensional array or an empty Map. The difference between map and Object

  • Obj keys can only use simple data types such as strings, numbers, or symbols
  • Map keys can be of any data type
  • Map does not have the same name collision problem, each object is a separate block of memory address
  • Map implements iterators that can be used for… Of traversal, Object does not
  • Map can get the length directly, Object can’t.
  • Meta-maps filled with maps can be expanded using ellipsis syntax, whereas Object cannot. Filling in elements preserves the order in which Object does not.

10.Spread Operator expand Operator (…)

You can expand strings, arrays, objects, etc

  • Convert strings to arrays

  • Convert collections to data

  • A combination of two arrays or objects

  • In functions, instead of arguments,

Rest parameters… The variable name

The rest argument is an array and cannot be followed by an argument, otherwise an error will be reported

Promise object

Promise is a solution to asynchronous programming by expressing asynchronous operations as a flow of synchronous operations, avoiding layers of nested callback functions. The Promise constructor is executed synchronously, and the THEN method asynchronously. It is in three states: pending, resolved, and rejected. The Promise constructor contains one parameter and a callback with resolve and reject parameters. Perform some operation (asynchronous, for example) in the callback, calling resolve if all is well, reject otherwise. You can call the promise.then() method for an instantiated Promise object, passing the resolve and reject methods as callbacks. The then() method takes two arguments, onResolve and onReject, which represent the current Promise object when it succeeds or fails.

Promise implementation principleFirst, promises have three states

Pending Specifies the initial state of an object instance when it is created

This can be interpreted as a state of success

Rejected = Rejected

Constructing a Promise instance requires passing a function to the Promise constructor. The function passed in requires two parameters, both of which are parameters of type function. Resolve and Reject, respectively.

The then method is used to specify the actions to be performed when the state of the Promise object changes. The first function (onpity) will be performed when the Promise object changes, and the second function (onRejected) will be performed when the Promise object changes.

When the state is resolve, it cannot be reject, and vice versa.

The shortcoming of Promise:

  1. It cannot be cancelled. Once it is created, it will be executed immediately. It cannot be cancelled halfway.
  2. Without a callback function, errors thrown inside a promise are not reflected externally
  3. When in the pending state, there is no way to know what stage of progress is currently in, whether it is beginning or ending

Promise.all()

After completing the asynchronous promise array, pass the completion result in the first function of then. The list argument is the arR array consisting of the img returned from all asynchronous THEN’s in the promise array. It can also be understood as adding the IMG from the THEN of each PROMISE object in the ARR in order to an array, and returning the array list after completion

Promise. All (requestPromises). Then (…). The catch (…). The then method is entered only when all requestPromises are resolved and all results are returned as an array. One failure and you’re in the catch. If a catch method is defined in a single request, then the catch method of promise.all is not included. Therefore, failed promises can be placed on a list of individual catches, and failed requests can be requested after a round of requests is completed.

Promise.race()

The arR () function passes the parameters returned from then of the first promise in the arR array to img, in the first function of promise.race().then().

New The process of instantiating a function

Call a function (new ClassA(…)) using the new keyword. )

  1. Create an empty objectVar obj={};
  2. Set the new object’s constructor property to the name of the constructor, pointing the new object’s __proto__ to the constructor’s prototypeObj.__proto__==ClassA.prototype
  3. Call the constructor with the new object, in which this points to the new instance object,ClassA.call(obj)
  4. Store the initialized address of the new object in the variable to the left of the equals sign.
  5. If the constructor return this or the return value is the basic type, number, string, Boolean, null, and undefined) or no return value, it returns a new instance object, if the value of a reference type, it returns the reference type.

ES5 call, apply, bind

  • In Js, call and apply are used to change the context in which a function is run, that is, to change the this reference inside the function body.
  • Call (object), function.apply(object), function.bind(object)()
  • The methods that call call and apply are executed immediately.
  • The bind method creates a new function that requires a () to execute, with the parameters passed in ()

Differences between ES6 and CommonJS modularity

What is JS modularity?

Js did not have the concept of modularity at the beginning, until Ajax was put forward, the front end can request data like the back end, the front end logic is more and more complex, there are many problems: global variables, function name conflict, dependency is not easy to deal with. Subexecuting functions were used to solve these problems. For example, classic jquery uses anonymous self-executing functions to encapsulate code and mount it all under the global jquery variable.

CommonJs thrives on nodeJs, where each JS file is a module and each module has its own scope. The module exports an object to module.exports. Use the require method to read the file and return its internal module.exports object. The problem with CommonJs is that it loads synchronously, which is normal on the server, but not in a browser full of asynchrony. There was a split in the community to accommodate the browser.

AMD (asynchronous module definition) The AMD specification defines modules through the define method and loads modules through the require method. RequireJS implements this specification. AMD has only one interface: DEFINE (ID? ,dependencies? ,factory); It specifies all dependencies (DEPs) when declaring the module and passes them to the Factory as parameters. If there are no dependencies, define simple modules (or stand-alone modules)

CMD (Common Module Definition) CMD is the normalized output of the module definition in SeaJS promotion.

Differences between AMD and CMD:

  1. For dependent modules, AMD executes early and CMD executes late. Since 2.0, however, RequireJS has also been deferred (handled differently depending on how it is written). CMD advocates as lazy as possible (loading as lazily as possible, also known as lazy loading, loading only when needed).
  2. CMD advocates dependency proximity (defining dependencies as they become available), while AMD advocates dependency front-loading (dependencies must be written in the first place).
  3. AMD API default is a when multiple use, CMD API strictly differentiated, advocating a single responsibility. For example, in AMD, require is divided into global require and local require, both called require. In CMD, there is no global require, but according to the completeness of the module system, seajs.use is provided to realize the loading and starting of the module system. In CMD, every API is simple and pure.

Es6 modular in ES6 did not come out before, the community developed a number of module loading schemes, the most important have CommonJS and AMD two, the former for the server, the latter for the browser, ES6 in the language standard level, the implementation of module functions, and the implementation is quite simple, Fully capable of replacing CommonJS and AMD specifications as a common module solution for browsers and servers. One of the big features of modularity in ES6 is to be as static as possible. An ES6 module is not an object. Instead, it explicitly specifies the output code through the export command, which is then input through the import command. Module functions are mainly composed of two commands: export and import. The export command specifies the external interface of the module, and the import command is used to input functions provided by other modules. Generally speaking, a module is an independent file. All variables inside the file cannot be accessed externally. If you want external variables to be able to read a variable inside the module, you must use the export keyword to output the variable.

There are three main scenarios for Javascript modularization:

  1. CommonJS

2. AMD / CMD 3. ES6 Differences between ES6 modules and CommonJS:

  • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.
  • The CommonJS module is run time loaded, and the ES6 module is compile time output interface.
  • The CommonJs module outputs a copy of the value, meaning that once a value is output, changes within the module do not affect that value.

You can see that common.js has changed the count, but the output remains the same. This is because count is a primitive type and is cached. You have to write it as a function to get the value of the internal variation. Module. exports in common.js

The output is 1,2,2

In ES6, it is written like this, using export and import

ES6 modules are referenced dynamically and do not cache. The contents of a module are bound to the module in which they are located. Values are loaded dynamically and cannot be copied.

** Es6 module features:

  1. Static, must be at the top, cannot use conditional statements, automatic strict mode
  2. Treeshaking and compilation optimizations, as well as scope enhancement in webpack3
  3. External can get real time values instead of cached values (reference instead of copy)

** The difference between ES6 modules and CommonJS modules:

  1. The CommonJS module prints a copy of a value. Once a value is printed, changes within the module do not affect the value. ES6 modules print references to the value.
  2. CommonJS modules are loaded at run time, ES6 modules are output interfaces at compile time and are called only when used.

** Es6 module and commonJS module similarities:

  1. Both can change the value of an object’s internal properties

Callback function:

Callback function: a function is passed as an argument to another function (here we call the otherFunction “otherFunction”), and the callback function is called in otherFunction.

$("#btn_1"). Click (function() {alert("Btn 1 Clicked"); });Copy the code
// Function click() {alert("Btn 1 Clicked"); } $("#btn_1").click(click);Copy the code

The callback function is not executed immediately. It will contain its function within a specific time point is “correction” (just like its name) to realize the basic principle of the callback function Using named or anonymous function as a callback function Like the previous example, the first method is the anonymous function as a callback (using the position parameters defined anonymous function as a callback function). The second way is to name the function as a callback (define a named function and pass the function name as a variable to the function)

Async: async callback hell: async callback hell: async callback hell: async callback hell: async callback hell: async callback hell: async callback hell

function a(functionb(){
    c(function d(){
    })
})
Copy the code

We found that the above code made heavy use of the callback function (passing one function as an argument to another) and had many}) ending symbols, which made the code look confusing.

How to solve callback hell

The first uses ES6’s Promise, which translates in Chinese as a Promise to return data to you at a future point in time.

Promise has three states: Pending/Reslove/Reject. A pending B resolve C reject D pending

At the same time, the three commonly used Promise methods then indicate that the data status changes to REJECT after asynchronous success. Reslove Catch indicates that the data status changes to Reject after asynchronous failure All encapsulates multiple unrelated promises into a single Promise object and returns an array of data using THEN.

But too much use of THEN can pose new execution-flow problems. So here comes our other hero, the Generator in ES6.

A Generator is a mechanism that makes efficient use of memory by looping through the computation and generating values. By working with promises, you can write asynchronous code more elegantly

Iterator: When we instantiate a generator function, the instance is an Iterator. You can use the next() method to start the generator and control whether the generator executes further.

Yield/Next: These are the best gay friends who control the order of code execution.

The yield statement is used to suspend code inside a generator function, while the generator function is still running and active, and its internal resources remain in the suspended state.

Calling the next() method on the iterator causes the code to continue execution from where it was paused.

Of course generators are not perfect and the syntax is hard to understand, so ES7 has launched async/await, how appropriate. The yield + Promise notation requires manual processing (success or failure) of the resolution we receive as a Promise, and ES7 provides async/await to eliminate this step

  1. A clear concept
    • Async functions are syntactic sugar for generator functions.
    • Async functions are generator functions*Replace async with yield and await.
  2. Improvements to generator with async functions
    • Built-in actuators that do not need to be manually executed using next().
    • An await command can be followed by a Promise object or primitive type value, and a yield command can only be followed by a Thunk function or Promise object.
    • The return value is Promise. When a non-promise is returned, async wraps it as a Promise. (Promise.resolve(value))
  3. role

The ultimate solution for asynchronous programming. 4. Async /await is an alternative to writing callback functions in asynchronous programming. (Write code synchronously to perform asynchronous operations)

The principle (order of execution) function executes and returns an await as soon as it encounters an await. Wait until the triggered asynchronous operation is complete (and the call stack is cleared), then execute the following statement in the function body. 【 Personal Understanding 】

  • The code following the await statement is equivalent to the callback function. (i.e., start from the next line of await as the contents of the callback function)
  • The callback functions are pushed into the MicroTask queue. When the main thread call stack is cleared, each callback function is fetched from the MicroTask queue and executed one by one.
  • Await just makes the code inside and after the current async function wait, not all the code is stuck here. Return “await” and execute the code after async.

Js prototype chain:

** What is a prototype chain?

  • Each object can have a prototype object, which can have its own prototype, and so on, forming a prototype chain. To find a particular property, we first look in the object, if not in its prototype, and if not in its prototype…… This operation is delegated to the entire prototype chain, which is what we call the prototype chain.
  • The end of the stereotype chain points to NULL, and undefined attributes on the stereotype chain return undefined
  • The Prototype property is unique to functions. It points from a function to an object. The prototype property is a pointer to an object whose purpose is to hold properties and methods shared by all instances.
  • Every JavaScript instance object (except null) has a property called __proto__, which points to the object’s prototype and is the prototype-chain way to find a function or object.
  • Each stereotype has a constructor property pointing to the associated constructor, and the instance stereotype points to the constructor

There are several ways to implement inheritance in Js:

  1. Stereotype chain inheritance (an instance of a parent class as a stereotype of a subclass)

Advantages:

Simple and easy to implement, new instances of the parent class and attribute subclasses can be accessed

Disadvantages:

You can add instance attributes to a subclass, but you need to add new stereotype attributes and methods after the new parent constructor

Multiple inheritance cannot be implemented

When creating a subclass instance, you cannot pass arguments to the superclass constructor

2. Borrow constructor inheritance (fake object, classic inheritance

) copies the instance attributes of the parent class to the child class

Advantages:

Resolved the problem of subclass constructors passing arguments to superclass constructors

Multiple inheritance can be implemented (call or apply multiple parent classes)

Disadvantages:

Methods are defined in constructors and cannot be reused

You cannot inherit stereotype properties/methods, only superclass properties and methods

3. Example Inheritance (original type inheritance)

Advantages:

There is no limit to the way to call, simple and easy to implement

Disadvantages:

You can’t inherit multiple times

4. Combinatorial inheritance

Call the constructor of the parent class, inherit the attributes of the parent class, and reuse the function by taking the parent class instance as the prototype of the subclass

Advantages:

Functions can be reused, there are no reference properties, they can inherit properties and methods, and they can inherit properties and methods from prototypes

Disadvantages:

The parent class is called twice, producing two instances

5. ES6 inheritance

ES5 inheritance and ES6 inheritance

Es5 inheritance starts by creating your own this pointer in a subclass, and finally adds methods to this

Child.prototype=new Parent() || Parent.apply(this) || Parent.call(this)

Es6 inheritance uses the keyword to first create an instance object of the parent class, this, and finally modify this in the subclass

Closure:

  1. What is a closure:

Closures are functions that have access to variables in the scope of another function. A closure is a collection of local variables of a function that continue to exist after the function returns. A closure is a function’s “stack” that is not released when the function returns, and we can also understand that these function stacks are allocated not on the stack but on the heap. Closures are generated when you define another function within a function. 2. Why:

  • Anonymous self-executing functions: We know that all variables without the var keyword are added to the attributes of the global object by default. Such temporary variables can have many disadvantages, such as: other functions may misuse these variables; This makes the global object too large, affecting access speed (because variable values need to be traversed through the prototype chain). In addition to using the var keyword every time a variable is used, we often encounter situations where a function only needs to be executed once and its internal variables do not need to be maintained and can be closed.
  • Result cache: We will encounter a lot of development situation, suppose we have a process is very time consuming function object, each invocation will take a long time, so we need to calculate the value of the stored, when this function is called, in the first place in the cache lookup, if can’t find, is calculated, and then update the cache and return values, if found, Simply return the found value. Closures do just that, because they do not free external references so that the values inside the function can be preserved.
  • Encapsulation: implement classes, inheritance, etc.

Use closures to output 1,2,3,4…. every second implementation

  • ES6 Let block-level scope
  • (function(I){})(I) where the first () returns an anonymous function and the second () executes immediately

Implement add(1)(2)(3) output 6

Advantages of closures

  • Variables can be reused without contaminating them
  • Global variables can be reused, but can easily pollute variables. Local variables are valid only in the local scope. They cannot be reused and will not pollute the variables. Closures combine the best of global and local variables.
  • Can be used to define private properties and private methods.

Disadvantages of closures

  • It takes up more memory than normal functions, leads to poorer web page performance, and is prone to memory leaks under IE (some ‘stubborn’ memory is allocated and the browser cannot reclaim it, resulting in insufficient memory later).

Js memory leak:

Memory leak is caused by negligence or error program fails to release the memory is no longer in use, in the memory leak is not exist on the physical memory disappear, but the application in the allocation of memory after a long period, due to design error, leading to the release of this memory was lost control of the segment memory, causing the waste of memory.

  1. An unexpected global variable. Js creates a reference to an undeclared variable on the highest global object
  2. console.log
  3. closure
  4. DOM leaks, we will generally use DOM. We’re going to take a variable reference and we’re going to cache it in the current environment
  5. Forgotten timers

Js garbage collection mechanism:

JS memory lifecycle:

  1. Allocate as much memory as you need
  2. Use allocated memory (read, write)
  3. Release and return them when they are not needed

Js garbage collection mechanism:

  1. The automatic garbage collection mechanism finds values that are no longer in use and then frees up memory. The garbage collector performs a dump operation at regular intervals.
  2. Js, the most commonly used are removed by marking algorithm to find which object is no longer continue to use, in the example above a = null is actually made a release reference operation, make a corresponding value originally lose reference, from execution environment, the value will be the next time the garbage collector performs operations were found and released. Therefore, dereferencing when appropriate is an important way to achieve better performance for your pages.

Mark clear

This is the most common method of garbage collection in javascript. When a variable enters the execution environment, it is marked as “enter environment”. When a variable leaves the environment, it is marked “out of the environment.” Logically, you should never free up memory occupied by variables that enter the environment, because they may be used whenever the execution stream enters the corresponding environment. The garbage collector runs by marking all variables stored in memory. It then unflags variables in the environment and variables referenced by them. Variables tagged after this point are considered to be ready for deletion because they are no longer accessible to variables in the environment. At last. The garbage collector does a memory cleanup, destroying the tagged values and reclaiming the memory they occupy.

Reference counting

Another less common garbage collection strategy is reference counting. The meaning of reference counting is to keep track of how many times each value is referenced. When a variable is declared and a reference type is assigned to the variable, the number of references to the value is 1. Conversely, if the variable containing a reference to that value obtains another value, the number of references to that value is reduced by one. When the number of references becomes zero, there is no way to access the value, so it can be reclaimed. This way, the next time the garbage collector runs, it frees the memory occupied by values that are referenced zero times.

The differences between Ajax, Fetch, and Axios:

Ajax Usage Steps

  1. Create an XmlHttpRequest object
  2. Call the open method to set the basic request information
  3. Set the data to send, send the request
  4. Registers the listening callback function
  5. Get the return value and update the page

But what does the readyState status code represent here? Here is the record:

0: not initialized, but an XHR instance has been created

1: The open() function is called

2: Send () has been called, but no response has been received from the server

3: Receiving data from the server

4: Completes the response

  1. Traditional Ajax values are XMLHttpRequest(XHR), the earliest technology to send back-end requests, which belongs to native JS. The core uses the XMLHttoRequest object, and if multiple requests are sequential, callback hell can occur.

Pros: Partial updates, native support, no need for plug-ins Cons: can break the browser’s back functionality, creating callback hell 2. Jquery Ajax is a wrapper around native XHR, plus added support for JSONP. Pros: Many cons: Still doesn’t solve callback hell. 3. Fetch is a substitute for Ajax, which appeared in ES6 and uses the Promise object in ES6. The code structure is simpler than Ajax, and the parameters are similar to Jquery Ajax. The syntax is concise and easy to understand. Support async/await based on promise implementation. The lower-level, richer API, which is divorced from XHR, is the drawback of the new implementation in the ES specification: only errors are reported for network requests, and 400,500 will be considered successful requests. The cookie is not configured by default. You need to add a configuration item. Timeout control is not supported. The progress of the request cannot be monitored. 4. Axios is an HTTP client based on Promise for browsers and Node.js, which is essentially a wrapper around XHR, but is based on the Promise implementation and complies with the latest ES specification. Advantages: Create XHR from browser, support PROMISE API, browser-side support to prevent CSRF(cross-site request forgeries), provide concurrent request interface, create HTTP request from Node.js, intercept request and response, transform request and response data, and automatically transform JSON data.

JS cross domain:

Cause of cross-domain: cross domain is caused by the browser’s same origin policy, refers to the interface address page request, must with the page url address in the same domain (the domain name, port, protocol), is to prevent a domain interface is other domain name under the illegal calls, web browser security restrictions on js.

There are two common ways for back-end solutions to cross domains:

JSONP:

By using the feature that script tag can cross domain, the function of the current script can be directly called back in the cross-domain script, that is, by dynamically creating a script, and then requesting a url with a parameter to achieve cross-domain communication. How do YOU get data across domains using JSONP in jQuery?

The first method is to set dataType to ‘jsonp’ in the Ajax function:

The second way to do this is with getJSON, just add the value to the addresscallback=?Parameters:

When you need to cross fields, create a script tag, add it to the head, set the SRC value of the script to the URL of another field, preferably with a random parameter to prevent WEB caching. Generate a tag like this:

<script type="text/javascript" src="http://abc.com/js.php?t=1234" ></script>  
Copy the code

Of course this should be done with document.createElement.

CORS

The server sets the HTTP response headerAccess-Control-Allow-OriginValue.

Questions about how cookies are carried across domain requests:

With the withCredentials: true setting, Cookie information is added to the Request header when Ajax is sent.

The server allows cookies by setting access-Control-allow-credentials = true in the response header.

Access-control-allow-origin :”” and access-control-allow-credentials “, “true” cannot be set to “*”. The value can only be a specific domain name.

These two methods rely heavily on the assistance of the back end.

<? Header (' access-Control-allow-Origin: *');Copy the code

How to use the front end to achieve cross-domain?

  1. A forward proxy means a server located between the client and the origin server. In order to get content from the origin server, the client sends a request to the proxy and specifies the destination (the origin server). The proxy then forwards the request to the original server and returns the content to the client.

The forward proxy serves the client. The client can access server resources that cannot be accessed by the forward proxy. The forward proxy is transparent to the client and opaque to the server, that is, the server does not know whether it is receiving access from the proxy or from the real client.

  1. In Reverse Proxy mode, a Proxy server receives Internet connection requests, forwards the requests to the Intranet server, and returns the results to the Internet client. In this case, the proxy server acts as a reverse proxy server.

A reverse proxy serves the server. The reverse proxy helps the server receive requests from clients, forward requests, and balance loads. The reverse proxy is transparent to the server and opaque to the client. That is, the client does not know that it accesses the proxy server, and the server knows that the reverse proxy serves it.

Summary: The forward proxy is the client proxy, that is, the intermediate server proxy client. The server does not know the actual initiating client. The reverse proxy is the server proxy, the intermediate server proxy server, the client does not know the actual service provider.

Simple comparison Using Charles and other forward proxy is relatively simple and requires less knowledge. However, its configurability is relatively weak and it is only suitable for small and medium-sized projects. Reverse proxies using Nginx are a bit more complex and require basic nginx configuration. However, it has strong configurability, supports URL regular matching and setting priority, and is suitable for complex projects.

Document.domain + iframe cross-domain: both pages are co-domain by js forcing document.domain to be the base primary domain.

Location. hash + iframe Cross-domain: A wants to communicate with B across domains through the middle page C. Three pages, different fields use iframe location.hash to transfer values, the same fields directly js access to communicate.

Window. name + iframe Cross-domain: The SRC attribute of iframe is used to transfer the cross-domain data from the outdomain to the local region. That is, the window.name of iframe is used to transfer the cross-domain data from the outdomain to the local region.

Deep copy and shallow copy:

The fundamental difference between a deep copy and a shallow copy is whether a copy entity of an object, rather than a reference, is actually retrieved. Deep and shallow copies are only for reference data types such as Object and Array.

  • Shallow copy – just copy the basic types of data, and a reference type data, will be after copy and reference, we called this copy “(shallow copy) shallow copy”, in other words, a shallow copy is just a memory address to be copied, if the object in the original address is changed, the shallow copy out the object will change accordingly.
  • Deep copy – creates a new memory location in the computer to store the copied objects. If the source object is changed, the copied object does not change.

The shallow copy of data is not independent. If the copied object is changed, the shallow copy object is also changed. After the deep copy, the data is completely independent and has no relationship with the copied object. Deep copy implementation:

  1. JSON.parse(JSON.stringify())

Json.stringify converts an object into a JSON string, and json.parse () parses the string into an object. As you go, new objects are created, and the object opens up a new stack for deep copy. While this approach can implement deep copies of arrays or objects, it cannot handle functions. 2. Handwritten recursive method Recursive method to implement the principle of deep cloning: traversing objects and arrays until they are all basic data types, and then to copy, that is, deep copy.

Asynchrony and asynchrony in Js

First of all, JS is a single-threaded language. In any case, there is only one thread to do things. The difference between synchronous and asynchronous is that the execution order of each process on this thread is different. All the tasks are divided into two kinds, one kind is the synchronization task, is to point to in the main thread synchronization task queue tasks, only the first, a task has been completed after to perform a task, an asynchronous task refers not to the main thread, and into the task queue task, only such as the main thread, the task has been completed task queue began to notice the main thread, request to perform a task, The task is executed on the main thread. Specifically, asynchronous execution is as follows,

  1. All synchronization tasks are executed on the main thread, forming an execution stack
  2. Outside of the main thread, there is a task queue in which an event is placed whenever an asynchronous task has a running result.
  3. Once all synchronous tasks in the execution stack are completed, the system reads the task queue to see which events are in it and which asynchronous tasks correspond to them. Then the wait state ends, the execution stack enters, and the execution begins.
  4. The main thread repeats the above three steps

Task queue is a queue of events, can also be understood as the message queue, IO devices to complete a task, the task queue, an event is added to the said relevant asynchronous tasks can enter the execution stack, the main thread reads a task queue, is to read one of the events, the events in this task queue, apart from the IO device events, It also includes the time generated by some users, such as mouse click, page scrolling and so on, which is relatively time-consuming. As long as the callback function of these events is established, when these events occur, they will enter the task queue and wait for the main thread to read.

Js macro and micro tasks and event loops:

Js, the task can be divided into macro and micro tasks, when hung tasks, js engines will all tasks according to the category assigned to each of these two queue, executed first tasks on the main thread and execution, will perform all the tasks in the task queue, and then remove the macro task queue in the first task, according to the main thread, All tasks in the microtask queue are executed in sequence. After that, all tasks in the microtask queue are executed in sequence. Then, a macro task in the macro task queue is selected to execute the main thread task and all its microtasks, and so on until all task queues are empty.

Browser environment:

Macro tasks include setTimeout, setInterval, requestAnimationFrame

Microtasks generally include process. NextTick, Promise. Then Catch Finally

Event loop in Js:

A macro task is executed first. After the execution, if there are any microtasks available, all the microtasks are executed and the next macro task is started. If there are no microtasks, the next macro task is directly executed until all tasks are completed.

Example: First, the browser executes js to enter the first macro task to enter the main thread and print console.log(‘1’) directly.

A setTimeout is encountered and dispatched to the macro task Event Queue

Process. nextTick is thrown into the microtask Event Queue

When a Promise is encountered, new Promise directly executes the output console.log(‘7’);

Execution THEN is distributed to the microtask Event Queue

The first macro task is finished, and the micro task printing 6,8 begins

After the first round of microtask execution is completed, execute the second round of macro events and execute setTimeout

Execute the main macro task first, then execute the micro task, print ‘2,4,3,5’.

The entire code goes through two event loops, and the complete output is 1,7,6,8,2,4,3,5,

Macro and micro tasks are executed in a different order in browser and Node.js environments

Event delegate in Js:

Event delegation uses event bubbling to manage all events of a certain type by specifying only one event handler.

How event delegation works: Event delegation is implemented by bubbling events, which start at the deepest node and propagate them up. For example, if you have a tree of nodes div>ul>li> A, for example, if you add a click event to the innermost element of a, the event will be executed layer by layer in the order a> Li >ul>div. There is a mechanism for adding a click event to the outermost element of a div, and ul within it, Li, when a triggers a click event, it bubbles up on the outermost div, so it’s all triggered, so that’s event delegate, delegate their parent to execute the event.

Application of event delegate:

Click on a different LI to display its contents

Traditional versus event delegate methods

In the traditional way, there are many DOM operations, and each click on LI requires traversing all li events

Event delegates, on the other hand, manipulate only the DOM currently clicked

Browser event mechanism

There are three stages of event propagation: capture, target object, and bubbling.

  1. Capture is the process by which an Event object is dispatched from the window to the parent of the target object.
  2. The Target phase is the phase when the event object is dispatched to the Target element, and event propagation terminates at this stage if the event type indicates that it does not bubble.
  3. The Bubbling phase, as opposed to capture, is the process from the parent of the target object to the window.

Calling stopPropagation at either stage will terminate propagation of the event.

Events bound to clicked elements occur in code order, while other unbound elements are triggered by bubbling or capturing. According to the W3C standard, a capture event is followed by a bubbling event. So the overall order of events is: non-target element capture -> target element code order -> non-target element bubble.

Js event binding:

  1. Embedded in the HTML tag

2. [‘ t? : n]

But if you want to execute more than one function at a time, this binding is not possible: because of the same event, multiple functions will be overwritten

3. Element. addEventListener (event name, function, bubble/capture)

The above two functions fA() and fB() will be executed without overwriting.

The first is the event type. It does not need the on prefix, but the event name should be “”.

The second argument is the function to call when the event occurs;

The third is Boolean true or false. (Default is false)

False code is handled with a bubbling stream of events, and is generally chosen as false.

True means that the code is handled as a stream of captured events and is not necessarily not recommended.

Js execution stack

JavaScript execution context: Execution context is the abstract concept of JavaScript parsing and runtime environment, JavaScript runs any code is run in the execution context, execution context consists of three cycles: create — run — destroy, focus on the creation part. The creation step (where the function is called but not executed) does three things

  1. Create a variable object, first initialize the function’s arguments object, promote the function declaration and variable declaration, and find the variables needed to run the function from near to far.
  2. Create a chain of scopes. A scope is a separate domain so that variables do not interfere with each other. Variables that are not currently defined in the scope become free variables. The free variable is searched up to the scope in which the function was created — “create,” not “call,” or undefined if it doesn’t end up. This invocation relationship between layers constitutes the scope chain.
  3. Make sure this points to this, apply, and call

JavaScript engine creates the execution stack to manage the execution context. The execution stack can be thought of as a stack structure for storing function calls, following the principle of “first in, last out”. There are three execution contexts in Js

  • The global execution context, by default, is the Window object in the browser, and this points to it in non-strict mode.
  • Function execution context. JS functions create a context every time they are called.
  • Eval executes the context. The Eval function generates its own context, which is not discussed here.

The JavaScript engine is single-threaded and all code is queued. 2. We start with global code, first creating the global execution context, and then pushing that execution context onto the execution stack. 3. Each time a function is executed, an execution context for that function is created and pushed to the top of the stack. When the function completes, the execution context exits from the bottom and waits for garbage collection. 4. Browser JS always accesses the execution context at the top of the execution stack. 5. There is only one global context, which is pushed out when the browser is closed

The difference between a process and a thread

  • Processes are the smallest unit of resource allocation and threads are the smallest unit of CPU scheduling
  • Threads move under a process (pure cars cannot run)
  • A process can contain more than one thread (a train can have more than one car)
  • It is difficult to share data between different processes (passengers on one train cannot easily move to another, such as station transfers)
  • Data is easily shared between different threads in the same process (it is easy to switch from car A to car B)
  • Processes consume more computer resources than threads (using more trains than cars)
  • Process will not influence each other, between a thread hang hang up will cause the entire process (a train will not affect to another train, but if a train on the middle of a car on fire, will affect all the carriages) process can be extended to more machine, process is the most suitable for multi-core (different train can open in more than one track, The cars of the same train cannot travel on different tracks.

The memory address used by a process can be locked, meaning that when a thread uses some shared memory, other threads must wait for it to terminate before they can use it. (train bathroom) -” Mutex”

  • The memory address used by the process can be used to limit the amount of memory used (e.g. restaurant on train, how many people are allowed to enter, if full, you have to wait at the door until someone comes out) – “semaphore”

Var array = array;

  1. Instanceof object instanceof constructor
alert(a instanceof Array); / / true,Copy the code

The variable instanceof type returns a Boolean value

The instanceof operator is used to determine whether the object pointed to by the constructor’s prototype property is on the prototype chain of another object to be tested

The main implementation principle of Instanceof is as long as the right variable’s prototype is on the left variable’s prototype chain. Thus, Instanceof iterates through the prototype chain of the left variable until it finds the prototype of the right variable and returns false if the lookup fails.

2. arr.__proto__===Array.PrototypeAmong them__proto__Is a property of an object instance that points to the prototype of the object

Prototype is the constructor property and points to the constructor’s Prototype

3. arr.constructor===ArrayWhere constructor is the attribute of the instance stereotype, pointing to the instance’s constructor

4. Object.prototype.toString().call(arr)Where the return value is the string ‘[Object Array]’

5. Array.isArray(arr)A new method in ES6 that returns true or false

Js array deduplicate method:

  1. Array.filter() + indexOf

2. Use the for… of + includes()3. Double for loop 4. Array.sort() then compares whether adjacent elements are equal to exclude duplicates. 5. for… Of + Object takes advantage of the fact that the attributes of the Object cannot be the same 6. ES6的new Set() Array to important use for… Of + Object, or ES6’s new Set(). For… Of + Object should be the most efficient (only in terms of the results of the current order of magnitude).

Js anti-shake and throttling:

Js anti-shake basic idea: when the event is triggered continuously, no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the set time, the delay will start again.The basic idea of throttling in JS is to specify a period of time within which the callback function that triggers an event can only be executed once. If the callback function is triggered multiple times within the period, only one time can take effect.