This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

This article is the foundation of the front end and will be followed by advanced articles

HTTP/HTML/browser

Let’s talk about HTTP and HTTPS

SSL encryption for HTTPS is implemented at the transport layer.

HTTP and HTTPS basic concepts HTTP: Hypertext transfer Protocol is the most widely used network protocol on the Internet. It is a client and server request and response standard (TCP). It is used to transfer hypertext from the WWW server to the local browser, which can make the browser more efficient and reduce network traffic. HTTPS: Is an HTTP channel for security purposes. Simply speaking, it is the secure version of HTTP, that is, SSL layer is added to HTTP. The security basis of HTTPS is SSL. The main role of HTTPS protocol is: to establish a secure information channel, to ensure the transmission of data, to ensure the authenticity of the website.

What’s the difference between HTTP and HTTPS? The data transmitted over HTTP is unencrypted, that is, in plain text. Netscape set up the SSL protocol to encrypt the data transmitted over HTTP. In simple terms, HTTPS is a network protocol built by HTTP and SSL for encrypted transmission and identity authentication. It is more secure than HTTP. The main differences are as follows:

  1. HTTPS requires a CA certificate, which is costly.
  2. HTTP is the hypertext transfer protocol, and information is transmitted in plain text. HTTPS is the SECURE SSL encryption transfer protocol.
  3. Generally speaking, the HTTP port is 80, and the HTTPS port is 443.
  4. HTTP links are simply stateless; HTTPS is a network protocol based on SSL and HTTP for encrypted transmission and identity authentication. It is more secure than HTTP.

Working principle of THE HTTPS Protocol When a client uses HTTPS to communicate with a Web server, perform the following steps:

  1. If the client accesses the server using HTTPS URLS, the Web server must establish SSL links.
  2. Upon receiving the client’s request, the Web server returns, or transmits, the site’s certificate, which contains the public key, to the client.
  3. The client and the Web server begin to negotiate the security level, that is, the encryption level, of the SSL link.
  4. The client browser establishes the session key based on the security level agreed by the parties, encrypts the session key using the public key of the website, and transmits the session key to the website.
  5. The Web server decrypts the session key using its private key.
  6. The server encrypts the communication with the client using the session key.

Advantages of THE HTTPS protocol

  1. The HTTPS protocol authenticates users and servers, ensuring that data is sent to the correct client and server.
  2. HTTPS is a network protocol based on SSL and HTTP for encrypted transmission and identity authentication. It is more secure than HTTP and prevents data from being stolen or changed during transmission, ensuring data integrity.
  3. HTTPS is the most secure solution in the current architecture, and while not absolutely secure, it dramatically increases the cost of man-in-the-middle attacks.
  4. In August 2014, Google tweaked its search engine algorithm and said that “HTTPS encrypted sites rank higher in search results than their HTTP counterparts.”

Disadvantages of THE HTTPS protocol

  1. HTTPS handshakes are time-consuming, increasing page load times by 50% and power consumption by 10% to 20%.
  2. HTTPS caches are not as efficient as HTTP and add data overhead.
  3. SSL certificates also cost money, and the more powerful certificates cost more.
  4. An SSL certificate must be bound to an IP address. One IP address cannot be bound to multiple domain names. Ipv4 resources cannot support such consumption.

TCP three-way handshake, in one sentence

Both the client and the server need to be able to send and receive separately, so a three-way handshake is required.

The three-way handshake can be simplified as: C initiates a request for connection S confirms, and C initiates a connection C confirms.

  1. First handshake: S can only confirm that it can accept the segment sent by C
  2. Second handshake: C can confirm that S has received the packet segment sent by S and that IT can accept the packet segment sent by S.
  3. Third handshake: S can confirm that C has received the packet segment sent by S.

TCP waves four times

Reference answer:

Because TCP connections are full-duplex, each direction must be closed separately. The principle is that when a party completes its data sending task, it can send a FIN to terminate the connection in that direction. Receiving a FIN only means that there is no data flowing in that direction. A TCP connection can still send data after receiving a FIN. The first party to close will perform an active close, while the other party performs a passive close.

  1. TCP A TCP client sends a FIN to shut down data transfer from the client to the server.
  2. When the server receives the FIN, it sends back an ACK confirming that the serial number is the one it received plus one. Like SYN, a FIN takes a serial number.
  3. The server closes the connection to the client and sends a FIN to the client.
  4. The client sends an ACK packet and sets the acknowledgement number to the receiving number plus 1.

Differences between TCP and UDP

Reference answer:

  1. TCP is connection-oriented, while UDP is connectionless that is, you don’t need to establish a link before sending data.
  2. TCP provides reliable services. That is to say, the data transmitted through the TCP connection, no error, no loss, no repetition, and in order to arrive; UDP does its best to deliver, that is, it does not guarantee reliable delivery. And because TCP is reliable, connection-oriented, and does not lose data, it is suitable for large data volume exchanges.
  3. TCP is byte stream oriented, while UDP is packet oriented, and network congestion does not slow down the transmission rate (thus causing packet loss for real-time applications such as IP telephony and video conferencing).
  4. TCP supports only 1-to-1, while UDP supports 1-to-1 and 1-to-many.
  5. The header of TCP is larger than 20 bytes, while UDP is only 8 bytes.
  6. TCP is a reliable connection-oriented transport, while UDP is unreliable.

WebSocket implementation and application

Reference answer:

What is the WebSocket? WebSocket is a protocol in HTML5 that supports persistent connections. HTTP does not support persistent connections. Http1.0 and HTTP1.1 do not support persistent linking. Keep-alive in HTTP1.1 combines multiple HTTP requests into one.

What kind of protocol is WebSocket and what are its advantages? The life cycle of HTTP is defined by a Request, which is a Response. In Http1.0, this HTTP Request ends. Improved in Http1.1, yes there is a connection: keep-alive, that is, multiple requests can be sent and multiple responses can be received within a single Http connection. However, it must be remembered that in Http, a Request can only have one Response, and this Response is passive, not active.

WebSocket is based on, or borrows, the Http protocol for part of the handshake, and the handshake phase is the same as Http. Let’s look at an implementation of the WebSocket handshake protocol, which is basically two properties, upgrade and Connection.

The basic request is as follows:

Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
// Add the following attributes:
1.Upgrade:webSocket
2.Connection:Upgrade
// Tell the server to send webSocket
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Copy the code

HTTP request mode, HEAD mode

Options: Allows the client to view the performance of the server, such as how many requests are supported by the server.

A picture URL access directly after downloading how to achieve?

The important parameters in the return header of a request for browser parsing are the parameters in the RETURN HTTP header of the OSS API documentation that determine the user’s download behavior.

In case of download:1. x-oss-object-type:
Normal
2. x-oss-request-id:
598D5ED34F29D01FE2925F41
3. x-oss-storage-class:
Standard
Copy the code

Talk about Web Quality (Accessibility)

An easy-to-use website is one that can be used by people with disabilities. Disabled users are those with disabilities or poor health. Use the Alt attribute: Sometimes the browser cannot display the image. The browser is a voice browser (for blind and visually impaired people). If you use the Alt attribute, the browser can at least display or read a description of the image.

What are some practical methods for BOM property objects?

Reference: What is Bom? A Bom is a browser object. What are the common Bom attributes?

Location object

Location.href -- Returns or sets the URL of the current document location.search -- returns the query string portion of the URL. case/ / such as http://www.xxx.com/xxx.go?id=5&name=xxx (?) the back of the included return? Id = 5 & name = XXXLocation.hash -- returns whatever follows the URL#, or empty location.host if there is no # -- returns the domain name part of the URL, For example www.dreamdu.com location.hostname -- returns the primary domain name part of the URL, for example dreamdu.com location.pathname -- returns the URL after the domain name. For example, HTTP:/ / www.dreamdu.com/xhtml/ / return/XHTMLLocation.port -- Returns the port portion of the URL. For example, HTTP:/ / www.dreamdu.com:8080/xhtml/ back to 8080Location. protocol - Returns the protocol part of the URL. For example, HTTP:/ / www.dreamdu.com:8080/xhtml/ return (/ /) in front of the content of the HTTP:Location.replace () -- Sets the URL of the current document and removes the URL location.replace(URL) from the history object's address list; Location.reload () -- Reloads the current pageCopy the code

The history object

History.go () -- Forward or back the specified number of pages history.go(num); History.back () -- back a page History.forward () -- forward a pageCopy the code

The Navigator object

Navigator.useragent -- returns a string representation of the userAgent header (that is, a string that includes browser version information, etc.Copy the code

Talk about the HTML5 Drag API

Reference answer:

Dragstart: The body of the event is the drag-dropped element, triggered when the drag-dropped element is started. Darg: The body of the event is the dragged element and is triggered when the dragged element is being dropped. Dragenter: The body of the event is the target element and is fired when the element is dragged into an element. Dragover: The event body is the target element and is triggered when it is dragged and moved within an element. Dragleave: The body of the event is the target element and is triggered when the drag and drop element is removed from the target element. Drop: The event body is the target element and is fired when the target element fully accepts the element being dragged and dropped. Dragend: The body of the event is the element to be dragged and is triggered at the end of the entire drag operationCopy the code

The way http2.0

First of all, the difference between HTTP and HTTPS: compared to HTTP, HTTPS is an HTTP protocol based on SSL encryption

In brief:

  1. Http2.0 is the first update based on Http1.0, which was released in 1999. Improved access speed (which can be used to request resources in less time and faster than HTTP1.0) allows multiplexing: Multiplexing allows multiple request-response messages to be sent simultaneously over a single HTTP/2 connection.
  2. Improved: in HTTP1.1, browser clients have a limited number of requests (connections) for the same domain at the same time, beyond which they will be blocked.
  3. Binary frame splitting: HTTP2.0 will split all the transmitted information into smaller pieces of information or frames and push them to the server side with a binary encoded header compression.

Added status codes 400 and 401 and 403

Reference answer:

  1. 400 Status code: The request is invalid. Cause: The field name and field type of the data submitted by the front end are not consistent with the entity in the background. The data submitted by the front end should be of JSON string type, but the object json. stringify is not converted into a string. Solution: Serialize the obj object through json.stringify for consistency against the field name.
  2. 401 Status code: The current request requires user authentication.
  3. 403 Status code: The server has received the request but is refusing to execute it.

Fetch Causes two requests to be sent

When a post request is sent, it is always sent 2 times. The first time the status code is 204, and the second time is successful. The simple reason is that when you use fetch’s POST request, the FETCH sends an Options request the first time, asking if the server supports the modified request header, and if it does, the actual request is sent the second time.

Cookie and session differences, localStorage and sessionStorage differences

Cookie, sessionStorage, localStorage: All stored in the browser side, and are the same source.

The Cookie and session: Both Cookie and session can be used to store user information. Cookie is stored on the client and session is stored on the server. Because Cookie stored on the client may be stolen, Cookie is generally used to store insensitive information, such as the website theme set by the user. A session can be stored in a file, a database, or in memory. A cookie can be set when the server responds to a request, or it can be set by the client through javascript. The cookie will be sent to the client at the head of the HTTP request. Cookies generally have a size limit on the client, usually 4K, and many browsers limit the number of cookies a site can store to 20.

How can cookies be encoded? EncodeURI ()

The cookie is used to save the login status of the user. For example, storing the user ID in a cookie so that the user does not need to log in again the next time they visit the page, as many forums and communities now offer. You can also set an expiration time for cookies. When the expiration time expires, cookies will disappear automatically. As a result, the system can often prompt the user for how long to stay logged in: common options are one month, three months, one year, etc. Track user behavior. For example, a weather forecast website can display local weather conditions based on the area selected by the user. If each time you need to choose the location is cumbersome, when the use of cookies will appear very humane, the system can remember the last visit to the region, the next time to open the page, it will automatically display the weather situation of the last user’s area. Since everything is done in the background, such a page is as customized for a user, making it easy to customize the page. If the site offers the ability to skin or change the layout, then cookies can be used to record the user’s options, such as background color, resolution, etc. When the user visits next time, the interface style of the last visit can still be saved.

SessionStorage: only in the current browser window closed before the effective, naturally it is not possible to persist, localStorage: always effective, the window or browser closed has been saved, so used as persistent data; A cookie is valid only until the set cookie expiration time, even if the window or browser is closed. (Key: itself is a callback process, close the browser and disappear, session is a callback, when the page is different even if the same page opened twice, it is considered the same callback).

LocalStorage: localStorage is shared in all the same source Windows; Cookies are also shared across all the same origin Windows. (key: All same-origin Windows are shared and do not expire, and remain in effect regardless of whether the window or browser is closed).

Specific to distinguish

The following directions distinguish between cookie, localstorage and sessionStorage

1. Life Cycle:

  • Cookie: You can set the expiration time. Otherwise, the Cookie expires after the browser is closed by default
  • Localstorage: save it permanently unless it is manually cleared
  • Sessionstorage: Valid only for the current page session. It will be cleared after you close the page or browser

2. Store data:

  • Cookie: about 4K
  • Localstorage and sessionStorage: can save 5M information

3. HTTP request:

  • Cookies: They are carried in the HTTP header every time. Using cookies to store too much data can cause performance problems
  • The other two: only saved in the client that is the browser, and do not participate in the communication with the server

4. Ease of use:

  • Cookie: Need programmer own encapsulation, native Cookie interface is not friendly
  • The other two: you can use the native interface, or you can repackage

5. Application Scenario:

  • In terms of security, since each HTTP request carries cookie information, which wastes bandwidth, so cookies should be used as little as possible. In addition, cookies also need to be specified in scope, which can not be called across domains. There are many restrictions, but in terms of user identification and login, Cookie is better than storage, other cases can use storage, localstorage can be used to pass parameters on the page, sessionStorage can be used to save some temporary data, to prevent the user to refresh the page after the loss of some parameters.

Let’s talk about Web workers

In HTML pages, if the state of the page is not corresponding when the script is executed, the page does not become corresponding until after the script is executed. Web Worker is a JS that runs in the background, independent of other scripts, and does not affect your page performance. And the result is passed back to the main thread via postMessage. In this way, when complex operations are performed, the main thread is not blocked. How to create a Web Worker: Check whether the browser supports the Web worker, create a Web Worker file (JS, return function, etc.), and create a Web Worker object.

Understanding of HTML semantic tags

HTML5 semantic tags mean that the right tags contain the right content, are well structured and easy to read, such as nav for navigation bar, article, header, footer, etc.

Are HTML5 and CSS3 used much? Do you understand their new properties? Has it ever been used in a project?

Reference answer:

HTML 5:

  • Header Section footer aside nav Main article figure
  • The content element Mark highlights the progress
  • New form control Calander Date Time Email URL Search
  • New input type Color Date DateTime datetime-local email
  • Remove the outdated label big Font Frame Frameset
  • Canvas drawing, support inline SVG. Support MathML
  • Audio video source embed track
  • Local offline storage: Lists files that need to be stored offline locally in a manifest configuration file
  • The web store. LocalStorage and SessionStorage

CSS 3:

  • CSS3 border such as border-radius, box-shadow, etc.
  • CSS3 background such as background-size, background-origin, etc.;
  • CSS3 2D, 3D transformation such as transform;
  • CSS3 animation such as animation. reference

What is an iframe? What are the disadvantages?

Reference answer:

  • Definition: The iframe element creates an inline framework that contains another document
  • Tip: You can place the prompt text in between to prompt browsers that do not support iframe
  • Disadvantages:
  1. Blocks the onLoad event on the main page
  2. Search engines can’t read this page, not good for SEO
  3. The iframe and home page share the connection pool, and browsers have restrictions on the same area, which affects performance.

Doctype? How to distinguish strict mode from promiscuous mode? What do they mean?

A Doctype is declared at the beginning of the document and tells the browser how to render the page. There are two modes, strict mode and promiscuous mode.

  1. Strict mode typography and JS mode of operation operate at the highest standards supported by the browser.
  2. Promiscuous mode, backward compatibility, emulation of older browsers, prevent browsers from incompatible pages.

How do cookies defend against XSS attacks

A cross-site scripting attack (XSS) is an attack in which an attacker inserts javascript scripts in the HTML returned. To mitigate these attacks, you need to add set-cookie to the HTTP header: Httponly – This property prevents XSS, which prevents javascript scripts from accessing cookies. Secure – This property tells the browser to send cookies only when the request is HTTPS. The result should look like this: set-cookie =

…..

The difference between cookies and sessions

Reference answer:

  1. Cookie data is stored on the client and session data on the server.
  2. Cookies are not very secure. Someone can analyze the cookies stored locally and cheat them. For security reasons, you should use sessions.
  3. Setting a cookie time can make a cookie expire. But with session-deStory (), we will destroy the session.
  4. Sessions are saved on the server for a certain period of time. In terms of reducing server performance, cookies should be used when more access is required.
  5. A single cookie can hold no more than 4K of data, and many browsers limit the number of cookies a site can store to 20. The Session object has no restrictions on the amount of data that can be stored and can hold more complex data types.

In a word RESTFUL

A URL is used to locate the resource and HTTP is used to describe the operation.

Talk about Viewport and mobile layout

Reference: Check out this article: A comparison of common solutions for Responsive Layouts (Media Queries, Percentages, REM, and VW/VH)

Click has 300ms delay on ios, why and how to solve it?

Reference answer:

  1. Coarse, disable scaling<meta name="viewport" content="width=device-width, user-scalable=no">
  2. Using FastClick, the principle is: after detecting the Touchend event, immediately start to simulate the click event, and the browser 300 milliseconds after the actual departure of the event to block.

AddEventListener parameters

Reference answer:

addEventListener(event, function.useCapture) // Where,eventSpecify the event name;functionSpecifies the function to be executed when the event is fired; //useCaptureSpecifies whether the event is executed in the capture or bubble phase.Copy the code

This section describes the known status codes returned by HTTP

Reference answer:

100Continue to Continue. The client should proceed with its request101Switching Protocols Switching Protocols. The server switches protocols based on client requests. You can only switch to a more advanced protocol, for example, to a new version of HTTP200The OK request succeeds. Generally used for GET and POST requests201Created Created. The new resource was successfully requested and created202Accepted is Accepted. Request accepted, but not completed203The Authoritative Information is non-authoritative. The request succeeded. However, the meta information returned is not from the original server, but a copy204No Content No Content. The server successfully processed but did not return content. Ensure that the browser continues to display the current document without updating the web page205Reset Content Reset Content. The server processing succeeds. The user terminal (for example, browser) should reset the file view. Use this return code to clear the browser's form field206Partial Content Partial Content. The server successfully processed some of the GET requests300Multiple Choices. The requested resource can include multiple locations, and a list of resource characteristics and addresses is returned for the user terminal (e.g., browser) to select301Moved Permanently. The requested resource has been permanently moved to the new URI. The return message includes the new URI, and the browser is automatically directed to the new URI. Any new requests in the future should be replaced with the new URI302Found Temporary move. with301Similar. But resources are moved only temporarily. Clients should continue to use the original URI303See Other Check Other addresses. with301Similar. Use GET and POST requests to view304Not Modified Indicates that the file is Not Modified. The requested resource is not modified, and when the server returns this status code, no resource is returned. Clients typically cache the resources they have accessed by providing a header indicating that the client wants to return only resources modified after a specified date305 Use ProxyUse a proxy. The requested resource must be accessed through a proxy306Unused Indicates that the HTTP status code has been discarded307Temporary Redirect Indicates Temporary redirection. with302Similar. Use GET to request redirection400Bad Request The syntax of the client Request is incorrect. The server cannot understand it401An Unauthorized request requires user identity authentication402Payment Required reserved for future use403The Forbidden server understands the request from the requesting client, but refuses to perform the request404Not Found The server could Not find the resource (web page) requested by the client. Through this code, the website designer can set"The resource you requested could not be found"Personality page405Method Not Allowed Methods in client requests are disabled406The Not Acceptable server is unable to complete the request based on the content nature of the client request407 ProxyAuthentication Required The request requires the Authentication of the agent, and401Similar, but the requester should use a proxy for authorization408Request time-out The server waits for the Request from the client for a long Time and times out409The Conflict server may return this code if it completes a PUT request from the client, and the Conflict occurred while the server was processing the request410Gone The resource requested by the client does not exist.410Different from the404Available if the resource previously had been permanently deleted410Code that web designers can pass301The code specifies the new location of the resource411Length Required The server cannot process the request information sent by the client without content-length412Precondition Failed The Precondition information of the client request is incorrect413Request Entity Too Large The server rejects the Request because the requested Entity is Too Large to process. To prevent continuous requests from clients, the server may close the connection. If only the server is temporarily unable to process, a retry-after response is included414Request-uri Too Large The requested URI (USUALLY the URL) is Too long, and the server cannot process it415Unsupported Media Type The server cannot process the Media format that comes with the request416Requested Range not Satisfiable Client Requested range is invalid417Expectation Failed The server cannot satisfy Expect's request header500 Internal Server ErrorThe server had an internal error and could not complete the request501Not Implemented The server does Not support requests and cannot complete requests502Bad Gateway The server working as a Gateway or proxy received an invalid response from the remote server while attempting to execute the request503The server is temporarily unable to process client requests due to overloading or system maintenance. The length of the delay can be included in the server's Retry-After header504Gateway time-out The server that acts as the Gateway or proxy does not obtain requests from the remote server in a timely manner505HTTP Version Not Supported Indicates the Version of the HTTP protocol that the server does not supportCopy the code

Common HTTP request headers

Reference answer:

Head agreement instructions
Accept The acceptable response content-types.
Accept-Charset Acceptable character set
Accept-Encoding The encoding of acceptable response content.
Accept-Language List of acceptable response content languages.
Accept-Datetime An acceptable version of the response content in terms of time
Authorization Indicates the authentication information about the HTTP authentication resource
Cache-Control Specifies whether caching is used in the current request/reply.
Connection The type of connection that the client (browser) wants to use preferentially
Cookie An HTTP protocol Cookie Set by the previous server via set-cookie (see below)
Content-Length The length of the request body in base 8
Content-MD5 The binary MD5 hash value (digitally signed) of the contents of the request body, as a Base64 encoded result
Content-Type MIME type of the request body (used in POST and PUT requests)
Date The date and time the message was sent (in the “HTTP date “format defined in RFC 7231)
Expect Indicates that the client requires a specific behavior from the server
From The email address of the user who initiated the request
Host Indicates the domain name of the server and the port number that the server listens to. If the requested port is the standard port (80) for the corresponding service, the port number can be omitted.
If-Match The operation is performed only when the entity provided by the client matches the corresponding entity on the server. This is primarily used in methods such as PUT to update a resource only if it has not been modified since the user last updated it.
If-Modified-Since Return 304 unmodified if the corresponding resource has not been modified
If-None-Match Allows 304 NotModified to be returned if the corresponding content has not been modified, referring to the hypertext transfer protocol entity tag
If-Range If the entity has not been modified, return the missing part or parts. Otherwise, the entire new entity is returned
If-Unmodified-Since A response is sent only if the entity has not been modified since a certain time.
Max-Forwards Limits the number of times the message can be forwarded by the proxy and gateway.
Origin Initiate a request for cross-domain resource sharing (this request requires the server to include an access-control-allow-Origin header in the response, indicating the sources allowed by Access Control).
Pragma These fields may arise at any time in the request/response chain, depending on the specific implementation.
Proxy-Authorization Authentication information used to authenticate the agent.
Range Represents a request for part of an entity, with byte offset starting with 0.
Referer Represents the previous page visited by the browser, which can be thought of as a link to the previous page that brought the browser to the current page. The word “Referer” is actually the word “Referrer”, but it was misspelled in the RFC production standard, and has since been used incorrectly.
TE The encoding of the transport the browser expects to receive: the response protocol header can be used
Transfer-Encoding (you can also use “trailers” for the kind of chunking that you get when you deliver data) to indicate that the browser wants to receive some extra fields after the last zero-size block.
User-Agent The identity string of the browser
Upgrade Requires the server to upgrade to a higher protocol version.
Via Tell the server which agent made the request.
Warning A general warning that there may be an error in the entity content body.

Strong, negotiated cache

There are two kinds of caches: strong caches and negotiated caches, based on the header content of the response.

type Form of resource acquisition Status code Send to the server
Strong cache Get it from the cache 200 (from cache) No, access directly from cache
Negotiate the cache Get it from the cache 304 (Not modified) Yes, the server tells you whether the cache is available
  • Strong cache fields include Expires and cache-control. If cache-control and Expires both exist, cache-control has a higher priority than Expires.
  • Negotiation cache related fields include last-modified/if-modified-since, Etag/ if-none-match

When to use strong cache, negotiate cache

The resource on the server is not always fixed. In most cases, it will be updated. If we access the local cache at this time, the user will see the old resource. Therefore, we want the browser to request new resources when the resources on the server are updated, and use the local cache when the resources are not updated, in order to minimize the waste of resources caused by network requests.

You can refer to this article “HTTP Strong caches and Negotiated Caches”

About 304

Reference: 304: If the client sent a conditional GET request and the request was allowed, but the contents of the document have not changed (since the last access or based on the conditions requested), the server should return the 304 status code.

The difference between 301 and 302

Reference answer:

  • The requested resource has been Permanently Moved to a new location, and any future references to this resource should use one of the urIs returned by this response. If possible, clients with link editing capabilities should automatically change the requested address to the address returned from the server. Unless otherwise specified, this response is also cacheable.
  • 302 Found the requested resource is now temporarily responding to requests from a different URI. Since such redirects are temporary, the client should continue to send future requests to the original address. The response is cacheable only if it is specified in cache-control or Expires. The literal difference is that 301 is a permanent redirect, while 302 is a temporary redirect.
  • In the 301 scenario, domain name redirect is used. 302 is used for temporary redirects such as when an unlogged user visits the user center and redirects to the login page.

The front-end optimization

Reference answer:

  1. Reduce requests: Merge resources, reduce HTTP requests, Minify/gzip compression, webP, lazyLoad.
  2. Speed up requests: pre-resolve DNS, reduce the number of domain names, parallel loading, CDN distribution.
  3. Cache: HTTP cache requests, offline cache manifest, and offline data cache localStorage.
  4. Rendering: JS/CSS optimization, load order, server rendering, Pipeline.

Difference between GET and POST

Reference answer:

  1. The GET parameter is passed through the URL and the POST is placed in the request body.
  2. Get requests pass parameters in the URL with a length limit, while POST does not.
  3. Get is less secure than POST because the parameters are directly exposed in the URL and cannot be used to pass sensitive information.
  4. Get requests can only be URL-encoded, while POST supports multiple encoding modes
  5. Get requests are cached actively by the browser, while POST supports multiple encoding modes.
  6. Get request parameters are fully preserved in the browsing history, while POST parameters are not.
  7. GET and POST are essentially TCP links, no difference. However, due to HTTP regulations and browser/server restrictions, they are different in the application process.
  8. GET generates a TCP packet. POST generates two TCP packets.

HTTP supports methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, CONNECT

How do I draw a triangle

The triangle principle: the equalization principle of the border.

div {
    width:0px;
    height:0px;
    border-top:10px solid red;
    border-right:10px solid transparent;
    border-bottom:10px solid transparent;
    border-left:10px solid transparent;
}
Copy the code

What happens when you enter a URL into the address bar and the page renders?

This is a required interview question. After you enter the URL, you first need to find the server IP address of the URL domain. In order to find the IP address, the browser will first look for the cache and check whether there is any record in the cache. If there is no record in the hosts file of the system, it will query the DNS server. After getting the IP address of the server, the browser will construct an HTTP request according to the IP address and the corresponding port number. The request message will include the requested information, mainly is the request method, request and the attached data, and the HTTP request encapsulated in a TCP packet, the TCP packets will in turn after the transport layer, network layer, data link layer and physical layer to the server, the server parses the request to respond, Return the HTML to the browser, because HTML is a tree structure, the browser builds the DOM tree based on this HTML, in the process of building the DOM tree, if there is a JS script and external JS connection, it will stop building the DOM tree to execute and download the corresponding code, which will cause blocking. This is why it is recommended that the JS code should be placed after the HTML code, and then build a CSS object model tree based on the external CCTV, internal CCTV, and inline styles. The layout is to determine the location and size of each element, and then to render the page, because the HTML file will contain images, video, audio, and other resources, which will be downloaded in parallel during DOM parsing. The browser has a limit on the number of concurrent downloads per field, usually 4-6. Of course, in all of these requests we need to pay attention to the Cache, which is usually controlled by cache-control, last-modify, Expires and other header fields. The difference between cache-control and Expires is that cache-control uses a relative time, while Expires uses an absolute time based on the server. Because of the time difference, cache-control is usually used. If ETag is set in the Last response, the file will be forwarded to the server as if-none-match. If it is, last-modified will continue to be verified. If ETag is set in the Last response, last-modified will continue to be verified. If no ETag is set, last-Modified is verified and 304 is returned.

Enter the URL to the page loading display complete what happens?

Reference answer:

  • The DNS
  • A TCP connection
  • Sending an HTTP request
  • The server processes the request and returns an HTTP packet
  • The browser parses the rendered page
  • Connect the end of the

What two trees does the browser generate when it generates the page?

When the browser receives the corresponding HTML document from the server, it traverses the document nodes and generates the DOM tree. The CSSOM rule tree is generated by the browser parsing the CSS file.

Common HTTP headers

Reference answer: The HTTP header can be divided into generic headers, request headers, response headers, and entity headers. The generic header represents some general information, such as date, which represents the creation time of the packet. The request header is unique to the request packet, such as cookie, The response header is unique to the response packet, such as set-cookie, and the location associated with the redirect. The entity header describes the entity part, such as allow describes the executable request method. The content-type describes the subject type. Content-encoding Specifies the Encoding mode of the principal.

CSRF and XSS network attacks and defense

Reference answer:

  • CSRF: Cross-site request forgery, can be understood as the attacker steal the user’s identity, send the malicious requests in the name of the user, such as user login a web site, immediately in another TAB page views the attacker used in the manufacture of attack site, require access to this site just landing site, and send a malicious request, this time CSRF is produced, For example, the attacker uses an image, but the link to the image can modify the database. In this case, the attacker can operate the database in the user’s name by using a verification code, checking the REFER header in the HTTPS header, and using a token.
  • XSS: Cross-site scripting attacks, it is said the attacker by injecting malicious scripts, attacking when users browse the web, such as cookies, or other user identity information, can be divided into storage type and the type, storage type is an attacker input some data and stored in the database, to attack other visitors to see, Reflection type is not stored in the database, often manifested as the attack code in the URL address request parameters, defense for cookie set httpOnly attribute, check the user’s input, for special character filtering.

How to see the performance of the website

There are generally two ways to detect page loading time. One is passive testing: Is in the page is detected in a script or probes, when a user access page, probes collect data and analyze them back to the database automatically, another way of active monitoring, namely active structures, the distributed controlled environment, the simulation user access requests a page, take the initiative to collect performance data and analysis, on the detection precision, professional third-party tools better effect, Take performance geeks.

Introduction to THE HTTP Protocol (Features)

HTTP is a communication protocol based on TCP/IP to transfer data (HTML files, picture files, query results, etc.) HTTP is an object-oriented protocol belonging to the application layer, because of its simple, fast way, suitable for distributed hypermedia information system. It was proposed in 1990 and has been continuously improved and expanded after several years of use and development. Version 6 of HTTP/1.0 is currently used in the WWW, normalization of HTTP/1.1 is in progress, and the proposal of HTTP-NG(Next Generation of HTTP) has been proposed. The HTTP protocol works on a client-server architecture. The browser, as the HTTP client, sends all requests to the HTTP server, that is, the WEB server, through the URL. The Web server sends response information to the client based on the received request.

Web Performance optimization

Reference answer:

  • Reduce requests: Merge resources, reduce HTTP requests, Minify/gzip compression, webP, lazyLoad.
  • Speed up requests: pre-resolve DNS, reduce the number of domain names, parallel loading, CDN distribution.
  • Cache: HTTP cache requests, offline cache manifest, and offline data cache localStorage.
  • Rendering: JS/CSS optimization, load order, server rendering, Pipeline.

CSS

Reference: A rectangular area used to hold elements on a page. The box model in CSS includes IE box model and standard W3C box model. Box-sizing: border-box,padding-box,content-box

Standard box model:

IE Box model:

Differences: As can be seen from the figure, the main difference between the two box models is the scope of width. In the standard box model, width refers to the width of content, while in the IE box model, width representscontent+padding+borderThe width of these three parts, so there is a difference in the calculation of the width of the whole box:Left/right border+ left/right padding+widthIE box model box width: width introduced in CSS3box-sizingProperties,box-sizing:content-box;Represents the box model of IE,box-sizing:border-boxThis is the W3C standard box model and finally, as we mentioned earlier,box-sizing:padding-boxThe width of the property value includes the left and rightpadding+width.

Draw a 0.5px line

Reference answer:

Use meta viewport <meta name="viewport" content="Initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no"/> Transform: scale()Copy the code

Difference between the link tag and the import tag

Reference answer:

  • Link is an HTML tag, and @import is provided by CSS.
  • While the link is loaded at the same time as the page is loaded, the CSS referenced by @import is loaded after the page is loaded.
  • Link is an HTML tag and therefore not compatible, while @import is only recognized by IE5 +. Link style has more weight than @import style.

The difference between transition and animation

Reference answer: Most of the properties of Animation and Transition are the same. They both change the attribute values of elements over time. The main difference between them is that transition needs to trigger an event to change the attribute values, while Animation does not need to trigger any event to change the attribute values over time. And the transition is 2 frames from…. To, while animation can be frame by frame.

Flex layout

Reference: I will give you two links to ensure that you can understand.

The article links: www.ruanyifeng.com/blog/2015/0…

www.ruanyifeng.com/blog/2015/0…

BFC (block level formatting context for clear float, prevent margin overlap, etc.)

Reference answer:

  • The block-level formatting context is a separate render area and has certain layout rules.
  • The BFC region 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, the float element is also calculated

Those elements generate BFC:

  • The root element
  • Elements whose float is not None
  • Elements whose positions are fixed and Absolute
  • Display inline-block, table-cell, table-Caption, Flex, inline-Flex elements
  • Overflow is not visible element

Vertical center method

Reference answer:

/ / (1)marginCSS: div{width:400px;
    height: 400px;
    position: relative;
    border: 1px solid # 465468;
}
img{
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
html:
<div>
    <img src="mm.jpg"Word-wrap: break-word! Important; "> < div style =" box-sizing: border-box0Margin:0It is possible to discenter the document flow.Copy the code
/ / (2)marginNegative method.container{
    width: 500px;
    height: 400px;
    border: 2px solid # 379;
    position: relative;
}
.inner{
    width: 480px;
    height: 380px;
    background-color: # 746;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -190px; /* half of the height */
    margin-left: -240px; /* half of width */} // Add: in fact, here can also be marin-topmargin-leftNegative values are replaced by PI/PItransform: translateX (-50%) andtransform: translateY (-50%)
Copy the code
(3)table-cell (not out of the document stream) // sets the parent elementdisplay:table-cell and vertical-align:middle. div{ width:300px;
    height: 300px;
    border: 3px solid # 555;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
img{
    vertical-align: middle;
}
Copy the code
/ / (4) usingflex// Set the parent element todisplay:flex and set align-items:center;justify-content:center;
.container{
    width: 300px;
    height: 200px;
    border: 3px solid # 546461;
    display: -webkit-flex;
    display: flex;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;
}
.inner{
    border: 3px solid # 458761;
    padding: 20px;
}
Copy the code

About JS animation and CSS3 animation difference

Reference answer: Render threads are divided into main thread and Streamitor thread. If CSS animation only changes transform and opacity, At this point, the entire CSS animation is completed in the Compositor Trhead (while the JS animation is executed in the Main Thread and then starts the compositor thread for the next step). Note that changing transform and opacity does not create a layout or paint.

The difference between:

  • Function coverage, JS is larger than CSS
  • Implementation/reconstruction difficulty is different, CSS3 is simpler than JS, performance optimization direction fixed
  • For low version browsers with poor frame rate performance, CSS3 can do natural degradation
  • CSS animation has natural event support
  • Css3 has compatibility problems

Talk about block elements and row elements

Reference answer:

  • Block element: occupies a single line and has an autofill parent element. You can set margin and pading as well as height and width.
  • Row elements: do not dominate a row, width and height are invalidated, and the padding and margin in the vertical direction are invalidated.

The text ellipsis of a multi-line element

display: -webkit-box
-webkit-box-orient:vertical
-webkit-line-clamp:3// Display the ellipsis on line overflow:hiddenCopy the code

Visibility =hidden, opacity=0, display: None

Reference answer:

  • opacity=0The element is hidden, but does not change the layout of the page, and if the element is already bound to some event, such as the click event, then clicking on the area will trigger the click event
  • visibility=hidden, the element is hidden, but the page layout does not change, but the events to which the meta has been bound are not triggered.
  • display=noneTo hide an element and change the layout of the page, you can think of it as removing the element from the page.

Double margin overlap problem (margin folding)

Multiple adjacent (sibling or parent) block elements of a common stream will overlap vertically.

The result of folding is:

  1. When two adjacent margins are both positive, the fold results in the larger value between them.
  2. When two adjacent margins are both negative, the fold results in a larger value of the absolute value of both.
  3. When the margins are one plus one minus, the fold is the sum of the two.

Position attribute comparison

Reference answer:

Fixed position: The position of the element is fixed relative to the browser window and does not move even if the window is scrolling. Fixed positioning makes the location of an element independent of the document flow and therefore does not occupy space. Fixed positioning elements overlap with other elements.

Relative: If you position an element relative, it will appear at its position. This 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: The position of an absolutely located element is relative to the nearest located parent, or if the element has no located parent, then its position is relative to < HTML >. Absolute positioning makes the position of an element independent of the document flow and therefore does not take up space. Absolute locates an element that overlaps with other elements.

Sticky localization: An element is located first according to the normal document flow and then relative to the element’s flow root (BFC) and containing block (the closest block-level ancestor element) in the flow. Then, the element positioning is shown as relative positioning before crossing a certain threshold, and then as fixed positioning.

Default location Static: The default value. Without positioning, the element appears in the normal flow (ignoring the top, bottom, left, right, or Z-index declarations). Inherit: specifies that the value of the position attribute should be inherited from the parent element.

Remove the floating

Reference answer:

  1. Use an empty element with the clear attribute

      
< div class="clear" style =" box-sizing: border-box; margin-top: 1em; } property to clear the float.

or
* /
.news { background-color: gray; border: solid 1px black; } .news img { float: left; } .news p { float: right; } .clear { clear: both; } <div class="news"> <img src="news-pic.jpg" /> <p>some text</p> <div class="clear"> < /div> </div> /** Pros: simple, less code, good browser compatibility. Disadvantages: Need to add a lot of non-semantic HTML elements, code is not elegant, not easy to maintain later. * / Copy the code
  1. Use the OVERFLOW property of CSS
/** Add overflow:hidden; Or overflow: auto; You can clear the float, and in IE6 you also need to trigger hasLayout, such as setting the container width and height for the parent element or setting zoom:1. After adding the overflow attribute, the float element returns to the container layer, raising the height of the container to clean up the float. * /
.news {
  background-color: gray;
  border: solid 1px black;
  overflow: hidden;  *zoom: 1;
 }

.news img {
  float: left;
 }

.news p {
  float: right;
 }

<div class="news">
    <img src="news-pic.jpg" />
    <p>some text</p>
</div>
Copy the code
  1. Adding a float property to the container of floating elements can clear the internal float, but this will make the whole float and affect the layout. This is not recommended.
  2. Use adjacent elements.
// Do nothing and addclearProperties..news {
  background-color: gray;
  border: solid 1px black;
}

.news img {
  float: left;
}

.news p {
  float: right;
}

.content{
  clear:both;
}

<div class="news">
    <img src="news-pic.jpg" />
    <p>some text</p>
    <div class="content"> < /div>
</div>
Copy the code
  1. Use CSS’s: After pseudo-element
/** Combine :after pseudo-elements (note that this is not a pseudo-class, but pseudo-elements, which represent the nearest element after an element) and IEhack, which is perfectly compatible with all major browsers. Add a ClearFix class to the float element container, and then add an after pseudo-element to the class to clean the float by adding an invisible Block element to the end of the element. * /
.news {
  background-color: gray;
  border: solid 1px black;
 }

.news img {
  float: left;
  }

.news p {
  float: right;
 }

.clearfix:after{
  content: "020"; 
  display: block; 
  height: 0; 
  clear: both; 
  visibility: hidden;  
 }

.clearfix {
  /* Trigger hasLayout */ 
  zoom: 1; 
 }

<div class="news clearfix">
    <img src="news-pic.jpg" />
    <p>some text</p>
</div>
Copy the code

Handling of overflow in CSS3

Text-overflow property where clip is the text to be clipped; Ellipsis table trimmed text for displaying ellipses; String uses the given string to represent the trimmed text.

Element of float, what is display

Display is block

A method to hide an element in a page

Reference answer:

display:none; visibility:hidden; opacity: 0; positionIf I move to the outside,z-indexCoating, covering, etc.1. opacity:0The element is hidden, but does not change the layout of the page, and if the element is already bound to some event, such as the click event, then clicking on the area will trigger the click event2. visibility: hidden, the element is hidden, but does not change the layout of the page, but does not trigger the event to which the element is bound3. display:noneTo hide the element and change the layout of the page, you can think of it as removing it from the page.Copy the code

Three column layout implementation, as much as possible to write, floating layout, the three div generation order has no impact

Reference answer:

  1. useFloat + margin:To divFloat: left, left divMargin - right: leftAdd attributes to the spacing px and center, right divMargin - left, leftPlus the width of the center plus the interval.
  2. useFloat + overflow:To divFloat: leftAnd div for rightoverflow:hidden. In this way two boxes float and the other box triggers the BFC to reach adaptive.
  3. useThe position:Parent div SettingsPosition: relative, three child div SettingsPosition: absolute, this must calculate the box width and spacing to set the position, compatibility is better.
  4. Use table to implement: parent div settingDisplay: tableTo set upBorder - spacing: 10 px// Set spacing, arbitrary value, child div setdisplay:table-cell, this method has good compatibility and is suitable for the situation of unknown height and width, but margin fails and design interval is troublesome.
  5. Flex implementation: Parent div SettingsDisplay: flex; Div Settings for left and centermargin-right; Then the right div will set Flex: 1; This is right adaptive, but flex compatibility is not good.
  6. Grid implementation: parent div settingDisplay: the gridTo set upgrid-template-columnsProperty, fixed the width of the first column, the second column, the third column auto,

Calc properties

Width: Calc (100%-10px); width: Calc (100%-10px);

Display: What is the difference between table and its own table

2. The table is displayed on the table. The CSS declaration for table allows an HTML element and its children to use the same table-based CSS layout as the table element. This makes it easy to define a cell’s boundaries, backgrounds, and styles without the semantic problems associated with tabbed tags like table. The reason why the table element is gradually phased out is that the file written with div+ CSS is smaller than the file written with the table edge, and the table must be displayed after the page is fully loaded, while div is displayed line by line, so the table is too nested and less concise than div.

Location method of z-index

Reference answer: The z-index attribute sets the position of a positioning element along the z-axis. If positive, the closer it is to the user; if negative, the further away it is from the user. The value of the z-index attribute is auto by default, the stack order is equal to the parent element, and number, inherit, the value of the z-index attribute is inherited from the parent element.

The difference between line-height and height

Word-break: break-all; word-break: break-all; word-break: break-all; word-break: break-all; word-break: break-all; word-break: break-all;

Set the background color of an element. What areas will the background color fill?

The background-color is set to fill the content, padding, and border areas of the element.

The priority of the property selector and pseudo-class selector

Reference: Property selectors and pseudo-class selectors have the same priority

The difference between inline-block, inline, and block; Why can I set width and height if IMG is inline

Reference answer:

  • A Block is a block-level element with a newline before and after it. It can be set to width, height, and margin/padding both horizontally and vertically.
  • Inline: Invalidates width and height, invalidates margin in the vertical direction, and invalidates padding in both the horizontal and vertical directions
  • Inline-block: allows you to set the width and height of the line. Margin /padding is available in both horizontal and vertical directions

Use CSS to create a coin rotation effect

Reference answer:

#euro {
    width: 150px;
    height: 150px;
    margin-left: -75px;
    margin-top: -75px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform-style: preserve-3d;
    animation: spin 2.5 s linear infinite;
}
.back {
    background-image: url("/uploads/160101/backeuro.png");
    width: 150px;
    height: 150px;
}
.middle {
    background-image: url("/uploads/160101/faceeuro.png");
    width: 150px;
    height: 150px;
    transform: translateZ(1px);
    position: absolute;
    top: 0;
}
.front {
    background-image: url("/uploads/160101/faceeuro.png");
    height: 150px;
    position: absolute;
    top: 0;
    transform: translateZ(10px);
    width: 150px;
}
@keyframes spin {
    0% {
    transform: rotateY(0deg);
    }
    100% {
    transform: rotateY(360deg); }}Copy the code

Do you know about redraws and rearranges, how to reduce redraws and rearranges, what are the ways to take a document out of the document stream

Reference answer: DOM changes affecting budget lodge geometrical properties such as high, wide browser to recalculate the elements of the geometry properties, the geometric properties of the other elements would also be affected, the browser needs to reconstruct apply colours to a drawing book, this process is called rearrangement, the browser will be affected part of the process of drawing on the screen is called re-paint, cause rearrangement to redraw the reasons are:

  1. Add or remove visible DOM elements,
  2. Change in element size position
  3. Browser page initialization,
  4. The size of the browser window has changed. Rearranging always leads to redrawing. Redrawing does not always lead to rearranging.

The methods to reduce redrawing and rearrangement are:

  1. Instead of doing DOM queries when layout information changes,
  2. With CSSText,className changes the properties once
  3. Using the fragments
  4. For elements that are rearranged multiple times, such as animations. Use absolute positioning to detach from the document flow so that it does not affect other elements

The grammar and basic uses of box-sizing

Reference answer:

box-sizingSpecifies two side-by-side framed boxes, syntax asbox-sizing:content-box/border-box/inherit
content-box: The width and height are applied to the element's content box, respectively, and the inner margins and borders of the element are drawn outside of the width and heightborder-box: The width and height of the element determine the frame box of the element,inherit: inherits from the parent elementbox-sizing
Copy the code

JavaScript

Error in parameter length of get request

Reference: Myth: We often say that there is a limit to the size of parameters for GET requests, while there is no limit to the size of parameters for POST requests. In fact, the HTTP protocol never specifies a GET/POST request length limit. The restriction on get request parameters is the source versus the browser or Web server, which limits the length of the URL. To clarify this concept, we must emphasize the following points again:

  1. The HTTP protocol does not specify the length limit of GET and POST.
  2. The maximum length of GET is displayed because the browser and web server limit the length of the URI.
  3. Different browsers and WEB servers limit the maximum length.
  4. If Internet Explorer is supported, the maximum length is 2083 bytes. If only Chrome is supported, the maximum length is 8182 bytes.

Add caching differences between GET and POST requests

A GET request is similar to a lookup process, where the user retrives data without having to connect to the database every time, so caching can be used. Unlike POST, which generally does modification and deletion work, it must interact with the database, so it cannot use caching. Get requests are therefore suitable for request caching.

Let’s talk about closures

In a nutshell, a closure is a function that can read variables inside other functions, or a child function that is called outside the scope of the parent function in which the child function is located.

Talk about class creation and inheritance

Reference answer:

// 1) Class creation (ES5) : add properties and methods to the function prototype.
// Create an Animal class:
// Define an animal class
function Animal (name) {
    / / property
    this.name = name || 'Animal';
    // Instance method
    this.sleep = function(){
    console.log(this.name + 'Sleeping! '); }}// Prototype method
Animal.prototype.eat = function(food) {
console.log(this.name + 'Eating:' + food);
};
// This generates an Animal class, which has methods and properties when transformed into an object.
// (2) Class inheritance -- prototype chain inheritance
// -- prototype chain inheritance
function Cat(){ }
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat.sleep());
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
/** prototype = "Animal"; /** prototype = "Animal"; /** Prototype = "Animal"; Features: Based on the prototype chain, both the instance of the parent class, but also the instance of the child class shortcomings: can not achieve multiple inheritance */
// (3) Construct inheritance: using the constructor of the parent class to enhance the instance of the child class is equivalent to copying the instance properties of the parent class to the child class (without the stereotype)
function Cat(name){
    Animal.call(this);
    this.name = name || 'Tom';
}
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
// Features: Multiple inheritance can be implemented
// Disadvantages: you can only inherit properties and methods from a parent instance, not from a stereotype.
/** (4) instance inheritance and copy inheritance instance inheritance: add new features to the parent class instance, as a subclass instance return copy inheritance: copy attributes and methods on the parent class elements on the above two practical not strong, not one example. * /
/** (5) Composite inheritance: equivalent to a combination of construct inheritance and prototype chain inheritance. Function reuse */ is achieved by calling the superclass construct, inheriting the properties of the superclass and retaining the advantages of passing parameters, and then using the superclass instance as the prototype of the subclass
function Cat(name){
    Animal.call(this);
    this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
// Properties: you can inherit instance properties/methods as well as stereotype properties/methods
// Disadvantages: the superclass constructor is called twice, generating two copies of the instance
/** (6) Parasitic combination inheritance: in parasitic mode, cut off the instance properties of the parent class, so that when the parent class construction is called twice, the instance methods/properties */ are not initialized twice
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
(function(){
// Create a class with no instance methods
var Super = function(){};
Super.prototype = Animal.prototype;
// Prototype the instance as a subclass
Cat.prototype = newSuper(); }) ();// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
// It is recommended
Copy the code

Talk about the flow of events on the front end

Interactions with javascript in HTML are event-driven, such as onclick, onScroll, and so on. You can add event listeners to the document or elements in the document to order events. To know when these events are invoked, you need to understand the concept of “flow of events.” What is an event flow: An event flow describes the order in which events are received from the page. The DOM2 level event flow consists of the following stages.

  • Event capture phase
  • In the target stage
  • Event bubble phase

AddEventListener: addEventListener is a new dom2-level event operation that specifies an event handler. This method takes three arguments: the name of the event to be processed, the function that acts as the event handler, and a Boolean value. This last Boolean parameter, if true, calls the event handler during the capture phase; If false, the event handler is invoked during the bubbling phase.

IE only supports event bubbling.

How do you let events bubble and then catch

Reference: In the DOM standard event model, it is capture first and then bubble. However, if you want to achieve the effect of bubble first and then capture, for the same event, monitor capture and bubble, respectively corresponding to the corresponding handler function, listen to the capture event, first delay execution, until the bubble event is captured and then execute the capture.

Talk about event delegation

Reference answer: introduction: event delegation is, not on the events occurred (dom) directly set up to monitor function, but in his father’s elements set up to monitor function, through the event bubbling, parent can listen to the child element event trigger, through sentenced to break the dom event element type, to make a different response.

For example, the most classic is the ul and Li tags event listening, for example, when we add events, we use event hosting mechanism, not directly added to the li tag, but added to the ul parent element.

Benefits: Suitable for dynamic element binding, new child elements will also have a listener function, and can also have an event trigger mechanism.

Talk about lazy loading and preloading of images

Reference answer:

  • Preload: Load images in advance and render them directly from the local cache when the user needs to view them.
  • Lazy loading: The main purpose of lazy loading is to reduce the number of requests or delay requests as a front end optimization of the server.

The nature of the two techniques: the two behave in opposite ways, one loading early, the other loading late or even not loading at all. Lazy loading relieves the pressure on the server front end, while preloading increases the pressure on the server front end.

Differences between mouseover and mouseenter

Reference answer:

  • Mouseover: Events are triggered when the mouse moves over an element or its children, so there is a repetitive, bubbling process. The corresponding removal event is mouseout.
  • Mouseenter: An event is raised when the mouse removes the element itself (which does not contain its children), so it does not bubble. The corresponding removal event is mouseleave.

What the new operator in JS does

The new operator creates an empty object that refers to the constructor’s prototype. The constructor returns this object.

Alter this pointer to a function (bind, apply, call)

The first argument of both functions is the same, indicating the object to be changed. The second argument, apply, is an array, and call, is arg1,arg2… In this form. Changing the this scope with bind returns a new function that does not immediately execute.

JS positions, such as clientHeight scrollHeight, offsetHeight, as well as the scrollTop, offsetTop, what is the difference between clientTop?

Reference answer:

  • ClientHeight: represents the height of the visible area, excluding the border and scrollbar.
  • OffsetHeight: indicates the height of the visible area, including the border and scrollbar.
  • ScrollHeight: represents the height of all areas, including those that are hidden by scrolling.
  • ClientTop: Indicates the thickness of the border border, which is typically 0 if not specified.
  • ScrollTop: Height hidden after scroll. gets the height of the object from the top relative to the parent coordinate (the CSS positioned element or body element) specified by the offsetParent property.

JS drag and drop function implementation

Reference answer:

  1. First of all, there are three eventsMousedown, mousemove, mouseup
  2. When the mouse is clicked and pressed, you need a tag to indicate that it has been pressed, so you can execute the specific method in mousemove.
  3. ClientX and clientY mark the coordinates of the mouse, respectively the x-coordinate and y-coordinate, and we use offsetX and offsetY to represent the initial coordinates of the element. The example of movement should be: the coordinate when the mouse moves – the coordinate when the mouse is pressed. In other words, the positioning information is: the coordinate when the mouse moves – the coordinate when the mouse presses down + the offetLeft under the initial condition of the element. The other thing that’s also fundamental is that when you drag and drop you’re absolutely positioned, you’re changing the left and the left in the absolute position

Top is equivalent. Add: It can also be done with HTML5 Drag and drop.

The method of loading JS asynchronously

Reference answer:

  • If your script does not change the contents of the document, add the defer property to<script>Tag in order to speed up the processing of documents. Because the browser knows it will be able to safely read the rest of the document without executing the script, it will defer interpretation of the script until the document has been displayed to the user.
  • The async, HTML5 property only applies to external scripts, and if in IE, both defer and async exist, then defer has higher priority and the script will execute when the page completes. Create a script tag and insert it into the DOM.

Ajax solves the browser caching problem

Reference answer:

  • Before the Ajax send requestanyAjaxObj.setRequestHeader("If-Modified-Since","0").
  • Before the Ajax send requestanyAjaxObj.setRequestHeader("Cache-Control","no-cache").
  • Add a random number to the end of the URL: "fresh=" + Math.random().
  • Add a time rub after the URL:"nowtime=" + new Date().getTime().
  • If you’re using jQuery, you can just do this$.ajaxSetup({cache:false}). So all of the Ajax on the page will execute this statement but there’s no need to save the cache record.

JS throttling and shockproof

Reference answer:

Debouncing: The anti-shaking technology combines multiple calls in sequence into one, that is, the number of times the events are triggered in a specified amount of time.

// Anti-jitter function

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function () {
            timeout = null ;
            if(! immediate) func.apply(context, args); };varcallNow = immediate && ! timeout;clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
var myEfficientFn = debounce(function() {
    // The actual operation in scrolling
}, 250);
// Bind the listener
window.addEventListener(` `'resize'` `, myEfficientFn);
Copy the code

Throttling: Throttling functions that allow a function to be executed only once in X milliseconds.

'// Simple throttling function

function throttle(func, wait, mustRun) {
     var timeout,
         startTime = new Date(a);return function() {
        var context = this,
            args = arguments,
            curTime = new Date(a);clearTimeout(timeout);
       // If the specified trigger interval is reached, trigger handler
        if(curTime - startTime >= mustRun){
            func.apply(context,args);
            startTime = curTime;
        // Reset the timer when the trigger interval is not reached
        }else{
            timeout = setTimeout(func, wait); }}; };// The handler that you want to bind to the Scroll event
function realFunc(){
    console.log("Success");
}
// Use the throttling function
window.addEventListener('scroll',throttle(realFunc,500.1000));
Copy the code

JS garbage collection mechanism

The JS garbage collection mechanism is simple: find variables that are no longer in use and free the memory they occupy. There are two ways to do this: mark clearing and reference counting.

Mark clear: this is the most common way of recycling, when variables into the environment, enters mark this variable as the “environment”, logically, can never be released into the environment variables of the memory, can never be released into the environment variable memory, as long as the execution flow into the corresponding environment, they can use them. When leaving the environment, it is marked as leaving the environment. Garbage collector at run time will add tags to variables are stored in the memory is (all), and then remove the variables, the environment variables and the environment variables of the referenced variable (conditional remove tag), delete all the marked variables, delete the variable cannot be accessed in the environment variable so deleted, the garbage collector, The memory is cleared and the memory they occupy is reclaimed.

Reference counting: Reference counting is one of the less common garbage collection strategies. The meaning of reference counting is to keep track of the number of times each value has been referenced. When a variable has a reference type value assigned to it, the number of references to that value is 1. If the same value is assigned to another variable, the number of references to that value is increased by one. Conversely, if the variable containing the reference to this value takes another value, the number of references to this value is reduced by one. When the number of references to a value goes to 0, the value is no longer accessible and has no meaning, so it is released.

What does Eval do

The function is to parse the corresponding string into JS and execute it. The use of JS should be avoided because it is very performance consuming (2 times, once parsing into JS and once executing).

How to understand front-end modularity

Reference answer: Front-end modularity is complex file programming a separate module, such as JS files, etc., divided into separate modules to facilitate reuse (reuse) and maintenance (version iteration), this will lead to the problem of module interdependence, so there are commonJS specification, AMD, CMD specification, etc., And WebPack, a tool for JS packaging (compiling, etc.)

Talk about CommonJS, AMD, and CMD

A module is a file that implements a specific function. With a module, you can easily use other people’s code and load any module with any function you want. CommonJS: modularity starts on the server side, modularity is defined synchronously, each module is a separate scope, module output, modules.exports, module load require() imports the module. AMD: Chinese name meaning defined by the asynchronous module. RequireJS implements the AMD specification to address two major issues.

  1. Multiple files have dependencies, and the dependent file needs to be loaded into the browser before the dependent file
  2. The browser stops rendering the page when it loads, and the more files it loads, the longer the page will be unresponsive.
// Syntax: requireJS defines a function define, which is a global variable used to define modules.
// Examples of requireJS:
// Define the module
define(['dependency'].function(){
var name = 'Byron';
function printName(){
console.log(name);
}
return {
printName: printName
};
});
// Load the module
require(['myModule'].function (my){
my.printName();
}
RequireJS defines a function define, which is a global variable used to define modules:define(id? dependencies? ,factory)// Use the module loading function on the page:
require((dependencies), factory);Copy the code

To summarize the AMD specification: the require () function loads dependencies asynchronously so that the browser does not fail to respond, and the callback function it specifies will only be executed if the previous module loads successfully. Since the page will stop rendering when loading JS, we can load JS asynchronously, and if we need to rely on some of them, we can also asynchronously rely on them, and then execute some methods.

Object deep clone simple implementation

function deepClone(obj){
    var newObj= obj instanceof Array? [] : {};for(var item in obj){
        var temple= typeof obj[item] == 'object' ? deepClone(obj[item]):obj[item];
        newObj[item] = temple;
    }
    return newObj;
}
Copy the code

ES5 is a common way to clone objects. Notice that an array is an object, but it’s a little bit different from an object, so we’re going to start with some types, to determine whether newObj is an object or an array.

Implement a once function that is passed as arguments only to be executed once

function ones(func){
    var tag=true;
    return function(){
        if(tag==true){
            func.apply(null.arguments);
            tag=false;
        }
    return undefined}}Copy the code

Encapsulate native Ajax as promises

var myNewAjax=function(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.open('get',url);
        xhr.send(data);
        xhr.onreadystatechange=function(){
            if(xhr.status==200&&readyState==4) {var json=JSON.parse(xhr.responseText);
                resolve(json)
            }else if(xhr.readyState==4&&xhr.status! =200){
                reject('error'); }}})}Copy the code

JS listens for changes to object properties

// Let's assume we have a user object,
// (1) In ES5, you can use object.defineProperty to listen for existing properties
Object.defineProperty(user,'name', {set:function(key,value){}})// Disadvantages: If the ID is not in the user object, you cannot listen for the id change
// (2) In ES6, this can be implemented through a Proxy
var user = new Proxy({}, {set:function(target,key,value,receiver){}})User.id = user.id = user.id = user.id = user.id = user.id
Copy the code

How to implement a private variable that can be accessed using the getName method, but not directly

// (1) defineProperty
obj={
    name:yuxiaoliang,
    getName:function(){
        return this.name
    }
}
object.defineProperty(obj,"name", {// Cannot enumerate and cannot be configured
});
// (2) create a function
function product(){
    var name='yuxiaoliang';
    this.getName=function(){
        returnname; }}var obj=new product();
Copy the code

==, ===, and object.is

Reference answer:

/ / = = (1)
// Cast to number,null==undefined
""= =0 //true
"0"= =0 //true
""! ="0" //true
123= ="123" //true
null= =undefined //true
// (2)Object.js
// The main difference is +0! NaN = = NaN = 0
=== === === ===
Copy the code

The difference between setTimeout, setInterval, and requestAnimationFrame

Unlike setTimeout and setInterval, requestAnimationFrame does not require a setInterval. Most computer monitors refresh at 60Hz, which is roughly equivalent to 60 redraws per second. Most browsers limit redrawing operations to the frequency at which the display is redrawn, because there is no improvement in the user experience beyond that. Therefore, the optimal loop interval for the smoothest animation is 1000ms/60, which equals about 16.6ms. RAF uses the system time interval, which will not affect RAF because of the previous task, but will respond to the time interval when setTimeout and setInterval really run if the previous task is more than one.

Features:

  • The requestAnimationFrame gathers all the DOM operations in each frame in a single redraw or backflow, and the redraw or backflow intervals closely follow the browser refresh rate.
  • In hidden or invisible elements, the requestAnimationFrame will not be redrawn or reflow, which of course means less CPU, GPU, and memory usage
  • RequestAnimationFrame is a browser-specific API for animations. At run time, the browser automatically optimizes method calls and the animations are paused if the page is not active, saving CPU overhead.

Here is an article about requestAnimationFrame www.cnblogs.com/xiaohuochai…

Implement your own bind function

Reference answer:

// How it works: apply or call.
// (1) Initial version
Function.prototype.bind=function(obj,arg){
    var arg=Array.prototype.slice.call(arguments.1);
    var context=this;
    return function(newArg){
    arg=arg.concat(Array.prototype.slice.call(newArg));
    returncontext.apply(obj,arg); }}// (2) Consider the prototype chain
// Why? When creating a new bind function, you must inherit the original function
Function.prototype.bind=function(obj,arg){
    var arg=Array.prototype.slice.call(arguments.1);
    var context=this;
    var bound=function(newArg){
    arg=arg.concat(Array.prototype.slice.call(newArg));
    return context.apply(obj,arg);
}
var F=function(){}
// A parasitic combination inheritance is required
    F.prototype=context.prototype;
    bound.prototype=new F();
    return bound;
}
Copy the code

JS how to control the loading of a picture, after loading the next one

Reference answer:

// (1) Method 1
<script type="text/javascript">
    var obj=new Image();
    obj.src="http://www.phpernote.com/uploadfiles/editor/201107240502201179.jpg";
    obj.onload=function(){
    alert(The width of the image is:+obj.width+'; The height of the image is: '+obj.height);
    document.getElementById("mypic").innnerHTML="<img src='"+this.src+"' / >";
}
</script>
<div id="mypic">Onloading...</div>
// (2) Method 2
<script type="text/javascript">
    var obj=new Image();
    obj.src="http://www.phpernote.com/uploadfiles/editor/201107240502201179.jpg";
    obj.onreadystatechange=function(){
    if(this.readyState=="complete"){
    alert(The width of the image is:+obj.width+'; The height of the image is: '+obj.height);
    document.getElementById("mypic").innnerHTML="<img src='"+this.src+"' / >"; }}</script>
<div id="mypic">Onloading...</div>
Copy the code

Js

Reference answer:

Basic data types: Undefined, Null, Boolean, Number, String, Symbol reference data type: Object

JS judge type

Reference answer: judgment method: typeof (), instanceof, Object. The prototype. ToString. Call (), constructor and etc

Array to heavy

Reference answer:

  • The indexOf loop is deduplicated
  • The ES6 Set is unloaded. Array.from(new Set(array))
  • Object key/value pair deweighting; For example, Object[value1] = true. If Object[value2] exists, it indicates that the value is duplicate.

What are closures good for

Reference answer:

(1) What is a closure:

Closures are functions that have access to variables in the scope of another function. A closure is the set of local variables of a function, except that these local variables continue to exist after the function returns. A closure is a function “stack” that is not released after the function returns. We can also understand that the function stack is not allocated on the stack but on the heap. Closures occur when you define another function within a function.

(2) Why do you use it?

Anonymous self-executing functions: we know that all variables are added to the property of the global object by default if we do not add the var keyword. The global object is 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 we use a variable, we often encounter situations where we have functions that need to be executed only once, and whose internal variables need no maintenance, and can use closures. 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 the number of this letter, 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 value found. Closures do this because they do not release external references, so that the values inside the function can be preserved. Encapsulation: implement classes, inheritance, etc.

Can you talk about the language features of JS

Reference answer:

  • Runs on the client browser;
  • Direct parsing of executable code without precompiling;
  • Weak type language, more flexible;
  • Operating system-independent, cross-platform languages;
  • Scripting language, interpreted language

JS implementation across domains

JSONP: Through the dynamic creation of a script, and then request a reference url to achieve cross-domain communication. Document. domain + iframe cross-domain: Two pages through js forced to set document.domain as the base of the primary domain, the implementation of the same domain. Location. hash + iframe Cross-domain: If user A wants to communicate with user B across domains, user A communicates with user B through the middle page C. Three pages. Different domains pass values using the location.hash of iframe, and the same domains directly communicate with each other by JS access. Name + iframe cross-domain: the SRC attribute of the iframe is used to transfer cross-domain data from the outer domain to the local domain. The window.

PostMessage cross-domain: One of the window properties that can be operated across domains.

CORS: server set access-control-allow-Origin, front-end does not need to be set, if you want to take cookies, before and after the end need to be set. Cross-domain proxy: Start a proxy server to forward data

Rearrange and redraw. Let’s talk about it

Repaint or redraw: Once the box’s position, size, and other properties such as color, font size, etc. have been determined, the browser then draws each of these primary colors according to their own characteristics, rendering the content on the page. A redraw is a browser action triggered by a change in the appearance of an element. The browser redraws the element based on its new attributes, giving it a new look.

Condition that triggers redraw: Changes the element appearance attribute. Color, background-color, etc.

Note: Tables and their internal elements may require multiple computations to determine the values of their nodes in the rendered tree, taking twice as long as equivalent elements, which is one of the reasons we try to avoid using table layout pages.

Rearranging (refactoring /reflow /reflow) : When part (or all) of a rendered tree needs to be rebuilt due to changes in the element’s size, layout, hiding, etc., this is called reflow. Every page needs to be reflow at least once, when the page first loads.

Redraw and rearrange: During backflow, the browser disables the affected part of the rendered tree and reconstructs that part of the rendered tree. After backflow is complete, the browser redraws the affected part onto the screen. This process is called redraw. So, a rearrangement must lead to a redraw, but a redraw does not necessarily lead to a rearrangement.

The use of promise + Generator + Async

Promise addresses issues: callback hell Promise specification:

  • A promise can only be changed from “waiting” to “fulfilled” or “rejected”, but it cannot be reversed. At the same time, “fulfilled” and “rejected” cannot be changed into each other.
  • A Promise must provide a THEN method to access its current value, final value, and cause. Promise.then (resolve,reject),resolve, and reject are all optional parameters. If resolve or reject are not functions, they must be ignored, and the then method must return a PROMISE object.
/ * * use: To instantiate a PROMISE object, you need to pass in functions (with two arguments),resolve and reject, which determine the state internally. Resolve and reject functions can be passed in arguments that can be used in callbacks. Resolve and reject are both functions, and the arguments passed in are then Receive. */ in the callback function
var promise = new Promise(function(resolve, reject) {
setTimeout(function(){
resolve('All right, ha-ha-ha.');
});
});
promise.then(function(val){
console.log(val)
})
// Then accepts two functions, one for the resolve and the other for the reject state callbacks, and accepts the arguments passed in the instantiation.
promise.then(val= >{
//resolved
},reason= >{
//rejected
})
When no rejection is passed in the THEN, the error is translated into the catch function. If a rejection is passed, the error is translated into the catch and never gets into the catch. In addition, an error in a callback in a THEN will only be caught in the next level of the THEN and will not affect the state of the promise.*/
new Promise((resolve,reject) = >{
throw new Error('wrong')
}).then(null.(err) = >{
console.log(err,1);// Capture here
}).catch((err) = >{
console.log(err,2);
});

/ / contrast
new Promise((resolve,reject) = >{
throw new Error('wrong')
}).then(null.null).catch((err) = >{
console.log(err,2);// Capture here
});

// Error examples
new Promise((resolve,reject) = >{
resolve('normal');
}).then((val) = >{
throw new Error('Error in callback function')},(err) = >{
console.log(err,1);
}).then(null.(err) = >{
console.log(err,2);// Catch
});
// If the two are not equivalent:
// In this case, the catch catches not the error p1, but the error P2.
p1().then(res= >{
return p2()// P2 returns a promise object
}).catch(err= > console.log(err))
/** An error case for error capture: The function p1 instantiates the Promise object with a catch. If an error occurs, the catch will enter the catch, and a new one will be returned If an error occurs, it will enter the resolve callback in p1's then chain.*/
function p1(val){
return new Promise((resolve,reject) = >{
if(val){
var len = val.length;// If null is passed, an error occurs
resolve(len);
}else{
reject();
}
}).catch((err) = >{
console.log(err)
})
};
p1(null).then((len) = >{
console.log(len,'resolved');
},() = >{
console.log('rejected');
}).catch((err) = >{
console.log(err,'catch');
})
/** Promise callback chain: Promise can use returns and throws in callbacks, so a PROMISE object or other value can return in a then. It can also throw an error object, but if there is no return, undefined is returned by default. Then the callback argument in the then will receive undefined.*/
function p1(val){
return new Promise((resolve,reject) = >{
val==1? resolve(1):reject()
})
};
function p2(val){
return new Promise((resolve,reject) = >{
val==2? resolve(2):reject(); })};let promimse = new Promise(function(resolve,reject){
resolve(1)
})
.then(function(data1) {
return p1(data1)// If return is omitted, undefined is returned instead of p1, resulting in an error
})
.then(function(data2){
return p2(data2+1)
})
.then(res= >console.log(res))
Copy the code

The Generator function:

The generator function uses:

  • Execute in segments and can be paused
  • You can control phases and return values for each phase
  • You know if you’re going to the end
function* g() {
var o = 1;
yield o++;
yield o++;
}
var gen = g();
console.log(gen.next()); // Object {value: 1, done: false}
var xxx = g();
console.log(gen.next()); // Object {value: 2, done: false}
console.log(xxx.next()); // Object {value: 1, done: false}
console.log(gen.next()); // Object {value: undefined, done: true}
Copy the code

Generator and asynchronous control: Taking advantage of the paused effect of generator functions, you can write asynchronous operations in yield statements and then execute them later when the next method is called. This effectively means that you don’t need to write the callback function, because subsequent operations of asynchronous operations can be placed under yield statements and will be executed when the next method is called anyway. Therefore, an important practical use of Generator functions is to handle asynchronous operations and override callbacks.

Async and async: async means that this is an async function, and await can only be used within this function. Await means waiting here for the result of the asynchronous operation to return before continuing. Await is generally followed by an example of a promise object :async defines an asynchronous function that returns a promise. If async returns a synchronized value, the value is wrapped as a Promise that understands resolve, equivalent to return Promise.resolve(value). Await is used before an asynchronous operation to “wait” for the return value of the asynchronous operation. Await can also be used with a synchronized value.

let timer = async function timer(){
return new Promise((resolve,reject) = > {
setTimeout(() = > {
resolve('500');
},500);
});
}
timer().then(result= > {
console.log(result); / / 500
}).catch(err= > {
console.log(err.message);
});
// Return a synchronized value
let sayHi = async function sayHi(){
let hi = await 'hello world';
return hi; // Equivalent to return promise.resolve (hi);
}
sayHi().then(result= > {
console.log(result);
});
Copy the code

ES6 arrow function properties

The difference between an arrow function and a normal function is:

  • The arrow function does not have this, so we need to find the value of this by looking up the scope chain. This means that if the arrow function is contained by a non-arrow function, this is bound to this of the nearest non-arrow function,
  • The arrow function does not have its own Arguments object, but it has access to the arguments object of the enclosing function
  • It cannot be called with the new keyword, nor does it have a new.target value or stereotype

JS load process block, solution.

The async attribute of the script tag is specified. If async=”async”, the script executes asynchronously relative to the rest of the page (as the page continues to parse, the script will be executed) if async is not used and defer=”defer” : The script will execute when the page is finished parsing

Here basically completed and where did not tell the welcome to the big guy to criticize. Suggest liking + collecting