HTTP/HTML/browser
Let’s talk about HTTP and HTTPS
The SSL encryption of HTTPS is implemented at the transport layer.
Basic concepts of HTTP and HTTPS Hypertext Transfer Protocol (HYPERtext Transfer Protocol), the most widely used network protocol on the Internet, is a client and server request and response standard (TCP), used to transfer hypertext from the WWW server to the local browser transport protocol, it can make the browser more efficient, reduce network traffic. HTTPS: an HTTP channel that aims at security. In short, it is the secure version of HTTP, that is, ADDING SSL layer under HTTP. The SECURITY foundation of HTTPS is SSL, so SSL is required for encrypting details. The HTTPS protocol provides an information security channel to ensure data transmission and website authenticity.
What’s the difference between HTTP and HTTPS? Data transmitted through HTTP is unencrypted, that is, plaintext. Netscape uses SSL to encrypt data transmitted through HTTP. To put it simply, HTTPS is a network protocol constructed by HTTP and SSL that can be used for encrypted transmission and identity authentication. This protocol is more secure than HTTP. The main differences are as follows:
- The HTTPS protocol requires a CA certificate, and the cost is high.
- HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol.
- Generally speaking, the HTTP port is 80 and the HTTPS port is 443.
- HTTP links are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.
Working principle Of HTTPS When a client uses HTTPS to communicate with the Web server, perform the following steps:
- If the customer accesses the server using HTTPS urls, the Web server must establish SSL links.
- The Web server receives the request from the client and sends back, or transmits, the web site’s certificate, which contains the public key.
- The client and web server begin to negotiate the security level, or encryption level, of the SSL link.
- The client browser establishes the session key based on the agreed security level, encrypts the session key through the public key of the website, and transmits the session key to the website.
- The Web server decrypts the session key through its own private key.
- The server encrypts the communication with the client through the session key.
Advantages of THE HTTPS protocol
- Using THE HTTPS protocol, users and servers can be authenticated to ensure that data is sent to the correct clients and servers.
- HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP and protects data from theft and alteration during transmission, ensuring data integrity.
- HTTPS is the most secure solution under the current architecture, and while it is not absolutely secure, it significantly increases the cost of man-in-the-middle attacks.
- In August 2014, Google changed its search engine algorithm, saying that “HTTPS encrypted sites will rank higher in search results than comparable HTTP sites.”
Disadvantages of the HTTPS protocol
- HTTPS handshake is time-consuming, lengthens page load time by 50%, and increases power consumption by 10% to 20%.
- HTTPS caching is not as efficient as HTTP and increases data overhead.
- SSL certificates also cost money, and more powerful certificates cost more.
- An SSL certificate must be bound to an IP address. Multiple domain names cannot be bound to the same IP address. Ipv4 resources cannot support such consumption.
TCP three-way handshake, in one sentence
The client and server both need to be able to send and receive each other, so a three-way handshake is required.
From the picture, we can see that the three-way handshake can be simplified as: C initiates the connection request, S confirms the connection, and C confirms the connection. Let’s look at the function of each handshake:
- First handshake: S can only accept the packet segment sent by C
- Second handshake: C can confirm that S has received the packet segment and can accept the packet segment sent by S.
- Third handshake: S can confirm that C has received the packet segment.
TCP waved four times
Reference Answer:
Because the TCP connection is full-duplex, each direction must be closed separately. The principle is that a party can send a FIN to terminate the connection in that direction when it has finished sending its data. Receiving a FIN only means that there is no data flow in that direction, and a TCP connection can still send data after receiving a FIN. The party that closes first performs an active shutdown and the other party performs a passive shutdown.
- The TCP client sends a FIN to shut down the transfer of data from the client to the server.
- When the server receives the FIN, it sends back an ACK with the received sequence number plus one. As with the SYN, a FIN takes a sequence number.
- The server closes the client connection and sends a FIN to the client.
- The client sends an ACK packet for confirmation and sets the sequence number of the ACK packet to 1.
Differences between TCP and UDP
Reference Answer:
- TCP is connection-oriented while UDP is connectionless, that is, no link is required before sending data.
- TCP provides reliable services. That is to say, data transmitted through the TCP connection is error-free, not lost, not repeated, and in order to arrive; UDP does its best to deliver, i.e. reliable delivery is not guaranteed. And because TCP is reliable, connection-oriented, and does not lose data, it is suitable for large-volume exchanges.
- TCP is byte stream oriented, UDP packet oriented, and network congestion does not slow down the transmission rate (hence packet loss, for real-time applications such as IP telephony and video conferencing).
- TCP supports only 1 to 1, UDP supports 1 to 1 and 1 to many.
- TCP’s header is 20 bytes larger than UDP’s 8 bytes.
- TCP is connection-oriented, reliable transport, while UDP is unreliable.
The realization and application of WebSocket
Reference Answer:
What is the WebSocket? WebSocket is a protocol in HTML5 that supports persistent continuities. HTTP does not support persistent connections. Neither Http1.0 nor HTTP1.1 supports persistent links. Keep-alive in HTTP1.1 consolidates multiple HTTP requests into one.
What protocol is WebSocket? What are its advantages? The HTTP lifecycle is defined by a Request, i.e., a Request for a Response. In Http1.0, this HTTP Request ends. Improved in Http1.1, there is a connection: keep-alive, that is, multiple requests can be sent and multiple responses received within an Http connection. However, it must be remembered that in Http, a Request can only have one Response, and this Response is passive and cannot be initiated actively.
WebSocket is based on THE Http protocol, or borrows Http protocol to do part of the handshake, in the handshake phase is the same as Http. Let’s look at the implementation of a Websocket handshake protocol, basically two attributes, upgrade, connection.
The basic requirements are 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 a 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 the request type supported by the server, etc.
A picture URL access after direct download how to achieve?
In the return header of the request, the important parameter used for browser parsing is the return HTTP header in the OSS API documentation, which determines the user’s download behavior parameter.
Download case: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
A site that can be used by people with disabilities is an easy-to-use site. People with disabilities refer to users who have disabilities or are physically unhealthy. Use the Alt attribute: Sometimes the browser will not display the image. If you use the Alt attribute, the browser can at least display or read out a description of the image.
What are some useful methods of BOM attribute objects?
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 part 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 the content after URL#, or empty location.host if no # is present -- returns the domain part of the URL, For example www.dreamdu.com location.hostname - returns the main domain part of the URL, for example dreamdu.com location.pathname - returns the part after the domain name of the URL. For example, HTTP:/ / www.dreamdu.com/xhtml/ / return/XHTMLLocation. port - Returns the port part 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 () -- Set the URL of the current document, and remove the URL location.replace(URL) from the address list of the history object; Location.reload () -- Reload the current pageCopy the code
The history object
History.go () -- forward or backward the specified number of pages history.go(num); History.back () -- back one page history.forward() -- forward one pageCopy the code
The Navigator object
Navigator.useragent - returns a string representation of the userAgent header (that is, a string containing browser version information, etc.) navigator.cookieenabled - returns whether the browser supports (enables) cookiesCopy the code
Talk about the HTML5 Drag API
Reference Answer:
Dragstart: The event body is the element being dragged, which is triggered when the element is started to be dragged. Darg: The event body is the element being dragged and fired while the element is being dragged and dropped. Dragenter: The event body is the target element, fired when an element is dragged into an element. Dragover: The event body is the target element that is fired when it is dragged and moved within an element. Dragleave: The event body 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 dragged element. Dragend: The event body is the element being dragged and fired at the end of the entire drag-and-drop operationCopy the code
The way http2.0
First of all, the difference between HTTP and HTTPS: compared to HTTP, HTTPS is the HTTP protocol based on SSL encryption
Brief summary:
- Http2.0 is the first update based on http1.0 released in 1999. Improved access speed (which can be achieved with less time required to request resources and faster queries than HTTP1.0) allows multiplexing: Multiplexing allows multiple request-response messages to be sent simultaneously over a single HTTP/2 connection.
- Improved: In HTTP1.1, browser clients have a limit on the number of connections they can make to the same domain at any one time.
- Binary framing: HTTP2.0 will break all transmitted information into smaller messages or frames and binary encode them into compressed server-side push.
Add 400 and 401 and 403 status codes
Reference Answer:
- 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 of the background. The data submitted by the front-end to the background should be a JSON string, but the front-end does not convert the object json.stringify into a string. Workaround: Serialize the obj object through json.stringify against the field name for consistency.
- 401 Status code: The current request requires user authentication.
- 403 Status code: The server received the request, but refused to execute it.
The reason why fetch sent two requests
Q: When the fetch sends a POST request, it always sends two times, the first status code is 204, and the second one is successful. The reason is simple, because when you use the FETCH’s POST request, the fetch sends an Options request the first time, asking the server if it supports the modified headers, and then sends the real request the second time if the server does.
Cookie and session, localStorage and sessionStorage
Cookie, sessionStorage and localStorage have in common: they are all saved in the browser and are of the same origin.
The Cookie and session: Both cookies and sessions can be used to store user information. Cookies are stored on the client side, while sessions are stored on the server side. Because cookies stored on the client side may be stolen, cookies are generally used to store insensitive information, such as the website theme set by the user. Sensitive information is stored in session, such as user login information. Session can be stored in files, databases and memory. Cookies can be set when the server responds, or set by the client through JS. Cookies generally have a size limit on the client side, usually 4K. Many browsers limit the maximum number of cookies stored on a site to 20.
How are cookies encoded? EncodeURI ()
The cookie is used to save user login status. 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 is a feature that is now available in many forums and communities. Cookies can also set the expiration time, when the time limit is exceeded, the cookie will automatically disappear. As a result, the system can often prompt users for how long they want to stay logged in: common options are one month, three months, a year, and so on. Track user behavior. A weather website, for example, can display local weather conditions based on the region selected by the user. If it is cumbersome to choose the location every time, it will appear very humanized after using cookies. The system can remember the area visited last time, and when opening the page next time, it will automatically display the weather situation in the area where the user was last time. Because everything is done in the background, such pages are very easy to customize as if they were customized for a particular user. If the site provides the ability to change the skin or layout, you can use cookies to record the user’s options, such as background color, resolution, etc. When the user visits the interface next time, the interface style of the last visit can still be saved.
SessionStorage: only valid until the current browser window closed, naturally also cannot be persistent, localStorage: always valid, the window or browser closed is always saved, therefore used as persistent data; Cookies only remain valid until the set cookie expiration time, even if the window or browser is closed. (Key: it is a callback process, and disappears after the browser is closed. Session is a callback. If the page is different, even if the same page is opened twice, it is regarded as the same callback.)
LocalStorage: localStorage is shared in all origin Windows; Cookies are also shared across all the same origin Windows. (Key: Same-origin Windows are shared and not invalidated, and remain in effect whether the window or browser is closed or not).
Specific to distinguish
Let’s differentiate between cookie, localStorage, and sessionStorage in a few directions
1. Life Cycle
- Cookie: The expiration time can be set. Otherwise, the expiration time is set after the browser is closed
- Localstorage: permanently saved unless manually cleared
- Sessionstorage: valid only in the current web session, will be cleared after closing the page or browser
2. Data storage:
- Cookie: around 4K
- Localstorage and sessionstorage: stores 5M of information
3. HTTP request:
- Cookies: Are carried in HTTP headers each time. Using cookies to store too much data can cause performance problems
- The other two are saved only in the client, that is, the browser, and do not communicate with the server
4. Ease of use:
- Cookie: requires programmer encapsulation, native Cookie interface is not friendly
- Other two: can use the native interface, can also be encapsulated again
5. Application Scenarios:
- From the perspective of security, because each HTTP request carries cookie information back, which wastes bandwidth, so cookie should be used as little as possible, in addition to cookie also need to specify the scope, can not be called across the domain, a lot of restrictions, but user identification user login, Cookie is still better than storage, other cases can use storage, localStorage can be used to pass parameters in the page, sessionStorage can be used to save some temporary data, to prevent users from refreshing the page lost some parameters.
Talk about Web workers
In AN HTML page, if the state of the page is not corresponding when the script is executed, the page is not corresponding until the script is executed. Web workers are js running in the background, independent of other scripts, and do not affect your page performance. The result is passed back to the main thread via postMessage. This will not block the main thread during complex operations. How to create web workers: Check browser support for Web workers, create Web worker files (JS, postback functions, etc.), and create Web worker objects.
Understanding of HTML semantic tags
HTML5 semantic tag refers to the correct tag that contains the correct content, is well structured and easy to read, such as nav, article, header, footer, etc.
Are you using HTML5 and CSS3 a lot? Are you aware of their new properties? Have you ever used it in a project?
Reference Answer:
HTML 5:
- Header section footer Aside Nav main article figure
- The content element Mark highlights progress
- New form control calander Date Time Email URL Search
- New input type color date datetime datetime-local email
- Removed the outdated big Font Frame Frameset tag
- Canvas drawing supports inline SVG. Support MathML
- Audio Video Source Embed Track
- Local offline storage lists the files that need to be stored locally offline 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 conversion 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 frame that contains another document
- Prompt: You can place prompt text in between to alert certain browsers that do not support iframe
- Disadvantages:
- Blocks the onLoad event on the main page
- Search engines can’t read these pages, which is bad for SEO
- Iframe and the home page share the connection pool, and browsers have restrictions on the same area, which can affect performance.
Doctype? How to distinguish strict mode from promiscuous mode? What do they mean?
Doctype is declared at the top of the document and tells the browser how to render the page. There are two modes, strict mode and promiscuous mode.
- The strict mode typesetting and JS modes run to the highest standards supported by the browser.
- Promiscuous mode, backward compatibility, emulates older browsers and prevents browsers from not being compatible with pages.
How do cookies protect against XSS attacks
XSS (cross-site scripting) attacks are attacks where attackers embed javascript scripts in the returned HTML. To mitigate these attacks, a set-cookie is added 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 if the request is HTTPS. The result should be: set-cookie =
…..
The difference between cookies and sessions
Reference Answer:
- Cookie data is stored on the client and session data is stored on the server.
- Cookies are not very secure, so someone can analyze cookies that are stored locally and do cookie spoofing and you should use sessions for security purposes.
- Cookie expiration is enabled by setting the cookie time. But with session-destory (), we will destroy the session.
- Sessions are stored on the server for a certain amount of time. Cookies should be used to reduce server performance when the number of accesses increases.
- A single cookie can hold no more than 4K of data, and many browsers limit the number of cookies a site can hold to 20. Session objects have no limit on how much data can be stored, and can hold more complex data types.
In a sentence
It uses URLS to locate resources and HTTP to describe operations.
Talk about viewPort and mobile layout
Reference answer: Refer to this article: Comparison of common solutions for responsive layouts (media queries, percentages, REM and VW/VH)
Click has 300ms latency on ios, why and how to solve it?
Reference Answer:
- Bold, with zooming disabled
<meta name="viewport" content="width=device-width, user-scalable=no">
- With FastClick, the idea is that when a Touchend event is detected, it simulates the Click event and blocks any event that the browser actually starts 300 milliseconds later.
AddEventListener parameters
Reference Answer:
addEventListener(event, function.useCapture) // Where,eventSpecify the event name;functionSpecifies the function to execute when the event is fired. //useCaptureSpecifies whether the event is executed in the capture or bubble phase.Copy the code
This section describes the status codes returned by HTTP
Reference Answer:
100Continue to Continue. The client should continue with its request101Switching Protocols Switching protocol. The server switches protocols based on client requests. You can only switch to a more advanced protocol, for example, the new version of HTTP200The OK request succeeded. Typically used for GET and POST requests201Created Created. The new resource was successfully requested and created202Accepted. The request has been accepted, but processing is not complete203Authoritative Information is non-authoritative Information. The request succeeded. The meta information returned is not the original server, but a copy204No Content Indicates No Content. The server processed successfully, but did not return content. You can ensure that the browser continues to display the current document without updating the web page205Reset Content Resets the Content. If the server succeeds, the user terminal (for example, browser) should reset the document view. Use this return code to clear the browser's form field206Partial Content Indicates Partial Content. The server successfully processed some of the GET requests300Choose Multiple Choices. The requested resource can include multiple locations, and a list of resource characteristics and addresses can be returned for user terminal (e.g., browser) selection301Moved Permanently. The requested resource has been permanently moved to the new URI, the return message will include the new URI, and the browser will automatically redirect to the new URI. Any future new requests should be replaced with a new URI302Found temporary movement. with301Similar. But resources are moved only temporarily. The client should continue to use the original URI303See Other View Other addresses. with301Similar. Use GET and POST requests to view304Not Modified. The requested resource is not modified, and the server does not return any resources when it returns this status code. Clients typically cache accessed resources by providing a header indicating that the client wants to return only resources that have been modified after a specified date305 Use ProxyUse a proxy. The requested resource must be accessed through a proxy306Unused Indicates the Unused HTTP status code307Temporary Redirect Temporary redirection. with302Similar. Use GET to request redirection400Bad Request The syntax of the client Request is incorrect and cannot be understood by the server401An Unauthorized request requires user authentication402Payment Required for future use403The Forbidden server understands the request from the requesting client but refuses to execute the request404Not Found The server could Not find resources (web pages) based on the client's request. With this code, the website designer can set"The resource you requested could not be found"Personality page405Method Not Allowed The Method in the client request is disabled406The Not Acceptable server was 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 sent by the client for a long Time and times out409The Conflict server may return this code after completing the client's PUT request410The resource requested by the Gone client does not exist.410Different from the404If the resource previously had is now permanently deleted available410Code that website designers can pass301The code specifies the new location of the resource411Length Required The server cannot process requests sent by clients without Content-Length412Precondition Failed The client requested information413Request Entity Too Large The server rejects the Request because the requested Entity is Too Large. To prevent continuous requests from clients, the server may close the connection. If the server is temporarily unable to process it, a retry-after response is included414Request-uri Too Large The URI of the Request is Too long (usually the URL) for the server to process415Unsupported Media Type The server cannot process the Media format attached to the request416Requested range not satisfiable Client request range invalid417Expectation Failed The server cannot meet Expect's request header information500 Internal Server ErrorThe server had an internal error and could not complete the request501Not Implemented server did Not support the requested functionality and could Not complete the request502The Bad Gateway received an invalid response from the remote server when the server working as a Gateway or proxy tried to execute the request503Service Unavailable A 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 acting as a Gateway or proxy does not receive requests from the remote server in Time505HTTP Version Not Supported HTTP Version that the server does not support and cannot be processedCopy the code
Common HTTP request headers
Reference Answer:
Head agreement | instructions |
---|---|
Accept | The content-types of acceptable responses. |
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 time-dependent version of the response content |
Authorization | Authentication information of the resource to be authenticated in HTTP |
Cache-Control | Used to specify 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 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 content of the request body, the result encoded in Base64 |
Content-Type | MIME type of the request body (for 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 is asking the server to perform a specific behavior |
From | The email address of the user who initiated this request |
Host | Indicates the domain name of the server and the port number monitored by the server. If the requested port is the standard port (80) of 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 entity on the server. In methods such as PUT, a resource is updated only if it has not been modified since the last update by a slave user. |
If-Modified-Since | 304 unmodified is allowed 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 entity flag of the Hypertext Transfer protocol |
If-Range | If the entity has not been modified, the missing one or more parts are returned. Otherwise, return the entire new entity |
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 to indicate the source that Access Control allows). |
Pragma | Implementation-specific, these fields can be generated at any time in the request/response chain. |
Proxy-Authorization | Authentication information used to authenticate the agent. |
Range | Represents a request for a portion of an entity, byte offset starting at 0. |
Referer | Represents the previous page visited by the browser, which can be considered to have been brought to the current page by links from previous visits. “Referer” is actually the word “Referrer,” but the RFC misspelled the standard and used it instead. |
TE | The way the browser is expected to accept the transport is encoded: the response protocol header can be used |
Transfer-Encoding | (you could also use “Trailers” to say that the browser wanted to receive some additional fields after the last 0 block.) |
User-Agent | The browser identity string |
Upgrade | Requires that the server be upgraded to a higher version protocol. |
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 types of caching: strong caching and negotiated caching, depending on the header content of the response.
type | Form of resource acquisition | Status code | Send to the server |
---|---|---|---|
Strong cache | Fetch from the cache | 200 (from cache) | No, cache access directly |
Negotiate the cache | Fetch from the cache | 304 (not modified) | If yes, the server tells you whether the cache is available |
- Strong cache fields include Expires and cache-Control. Cache-control takes precedence over Expires if both exist.
- The negotiation cache fields are last-modified/if-modified-since, Etag/ if-none-match
When to use strong cache or negotiated cache
Because the resources on the server are not fixed all the time, most of the time it will update, this time if we also access the local cache, so for users, it is equivalent to the resource is not updated, users see the old resource; Therefore, we want to request new resources when the browser updates the resources on the server, and use the local cache when there is no update to minimize the waste of resources caused by network requests.
You can refer to this article which I personally feel good about “HTTP strong caching and Negotiated Caching”
About 304
304: If the client sends a conditional GET request and the request is granted, and the content of the document has not changed (since the last access or according to the conditions of the request), the server should return this 304 status code.
Difference between 301 and 302
Reference Answer:
- 301 Moved Permanently, 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 one that is returned from the server. Unless otherwise specified, the response is also cacheable.
- The resource requested by 302 Found now temporarily responds to the request 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 specified in cache-Control or Expires. The literal difference is that 301 is a permanent redirect and 302 is a temporary redirect.
- The common scenario of section 301 is domain name forwarding. 302 is used for temporary redirects such as unlogged users to the user center and redirects to the login page.
The front-end optimization
Reference Answer:
- Reduce request volume: merge resources, reduce HTTP requests, Minify/gzip compression, webP, lazyLoad.
- Speed up the request: pre-resolving DNS, reducing the number of domain names, parallel loading, CDN distribution.
- Cache: HTTP protocol cache request, offline cache manifest, offline data cache localStorage.
- Rendering: JS/CSS optimization, loading order, server-side rendering, pipeline.
GET and POST
Reference Answer:
- The GET argument is passed through the URL, and the POST is placed in the request body.
- Get requests pass parameters in the URL with length limits, whereas POST does not.
- Get is less secure than POST because parameters are directly exposed in the URL and therefore cannot be used to pass sensitive information.
- Get requests can only be url encoded, while POST supports multiple encoding methods
- Get requests are actively cached by the browser, while POST supports multiple encodings.
- Get request parameters are retained in the browser history, while POST parameters are not.
- GET and POST are essentially TCP links and are no different. However, due to HTTP regulations and browser/server restrictions, they are applied differently.
- GET generates a TCP packet; POST generates two TCP packets.
Add: HTTP supported methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, CONNECT
How to draw a triangle
Triangle principle: equalization principle of frame.
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
You type in a URL in the address bar, and when this page comes up, what happens?
This is an interview question. After entering the URL, you need to find the server IP address of the url domain name. To find this IP address, the browser first searches the cache to see if there is a record in the cache. If there is no record in the system’s hosts file. If there is no record in the cache, query the DNS server. After obtaining the IP address of the server, the browser constructs an HTTP request based on 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 corresponding HTML to the browser, because HTML is a tree structure, and the browser builds the DOM tree based on this HTML. During the DOM tree construction process, if it encounters JS scripts and external JS connections, 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 at the end of the HTML code, and then a CSS object model CSSOM tree should be constructed according to external mapping, internal mapping, and inline styles. After construction, the tree should be merged with the DOM tree into a rendering tree. The main thing here is to exclude non-visual nodes, such as script, Layout is mainly to determine the location and size of each element. Then render the page, because HTML files contain images, videos, audio and other resources. In the process of DOM parsing, these will be downloaded in parallel. Browsers limit the number of concurrent downloads per domain to 4-6. Of course, we also need to pay attention to caching in all requests. Caching is usually controlled by header fields such as cache-Control, last-modify, Expires, etc. The difference between cache-Control and Expires is that cache-Control uses relative time, whereas Expires uses absolute time on the server side. Because of the time difference, cache-Control is usually used. When requesting cached data, If the ETag value is set in the Last response, the ETag value will be sent to the server for verification. If the ETag value is set in the Last response, the last-Modified value will be verified by the server. If the ETag value is set in the Last response, the last-modified value will be verified. If no ETag is set, last-Modified is verified and 304 is returned.
Enter the URL to the page load display complete what happens?
Reference Answer:
- The DNS
- A TCP connection
- Sending an HTTP request
- The server processes the request and returns HTTP packets
- The browser parses the rendered page
- Connect the end of the
Which two trees do browsers generate when they generate a page?
Construct two trees, DOM tree and CSSOM rule tree. When the browser receives the corresponding HTML document from the server, it will traverse the document node to generate DOM tree. CSSOM rule tree is generated by the browser parsing CSS file.
Common HTTP headers
Reference Answer: The HTTP header can be divided into common headers, request headers, response headers, and entity headers. The common headers represent some common information. For example, Date represents the creation time of the packet. Cache-related if-Modified-since the response header is unique to the response message, such as set-cookie and location, entity header describes the entity part, allow describes the executable request method, content-Type describes the subject type, Content-encoding Specifies the Encoding mode of the body.
CSRF and XSS network attack 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 attack site uses a picture, but the link of the picture can modify the database, then the attacker can operate the database in the name of the user. In terms of defense methods, use the verification code, check the REFER in the HTTPS header, and use the 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, Reflective words are not stored in the database, often shown as the attack code in the URL address of the request parameters, defensive words for cookie set httpOnly attribute, check user input, special character filtering.
How to see the performance of the site
There are generally two ways to detect the page load time, one is passive to measure: 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 the performance geek.
Introduction to THE HTTP protocol (Features)
HTTP is a communication protocol based on TCP/IP to transfer data (HTML files, image 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 put forward in 1990. After several years of use and development, it has been constantly improved and expanded. Currently the sixth version of HTTP/1.0 is used in the WWW. The standardization of HTTP/1.1 is under way, and the proposal of HTTP-NG(Next Generation of HTTP) has been put forward. The HTTP protocol works on a client-server architecture. As the HTTP client, the browser sends all requests to the HTTP server, namely 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 request volume: merge resources, reduce HTTP requests, Minify/gzip compression, webP, lazyLoad.
- Speed up the request: pre-resolving DNS, reducing the number of domain names, parallel loading, CDN distribution.
- Cache: HTTP protocol cache request, offline cache manifest, offline data cache localStorage.
- Rendering: JS/CSS optimization, loading order, server-side rendering, pipeline.
CSS
Summary: 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 (3 values) : border-box,padding-box,content-box
Standard box model:
IE box model:
Difference: The main difference between the two box models is the range of width. In the standard box model, width refers to the width of the content part, while in the IE box model, width refers to the content partcontent+padding+border
The width of the three parts, so that there is a difference in calculating the width of the whole box:Left/right border+ left/right padding+width
The box width of IE box models: width was introduced in CSS3box-sizing
Properties,box-sizing:content-box;
Represents the W3C standard box model,box-sizing:border-box
And finally, as we mentioned earlier,box-sizing:padding-box
, the width of the property value includes 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(); /> border-imageCopy the code
The difference between link tag and import tag
Reference Answer:
- Link is an HTML tag, while @import is provided by CSS.
- When the page is loaded, link is loaded at the same time, and the CSS referenced by @import is loaded after the page is loaded.
- Link is an HTML tag, so it is not compatible, while @import is only recognized above IE5. Link style has a higher weight than @import.
Transition and animation
Reference Answer: Animation and Transition have most of the same properties. They both change the value of an element’s properties over time. The main difference is that Transition needs to trigger an event to change its properties, while Animation does not need to trigger any events to change its properties over time. And transition to 2 frames, from…. To, and animation can do it frame by frame.
Flex layout
Reference answer: This will not say more to 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, preventing margin overlap, etc.)
Reference Answer:
- A block-level formatting context is a separate rendering area with certain layout rules.
- The BFC area does not overlap with the float box
- The BFC is a separate container on the page, and the child elements do not affect the outside
- When calculating the height of the BFC, floating elements are also involved in the calculation
Which elements generate the BFC:
- The root element
- Float is an element that is not None
- Position is an element of fixed and absolute
- Display inline-block, table-cell, table-caption, flex, inline-flex element
- Overflow is not a visible element
Vertical center method
Reference Answer:
/ / (1)margin:auto CSS: 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"> </div> // position as up, down, left, and right0Margin:0It is possible to center out of 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; /*height */
margin-left: -240px; /* half of width */} // Add: you can also add marin-top 和margin-leftNegative values are replaced by, //transform: 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, the element can be centered vertically. 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 to 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
The difference between JS animation and CSS3 animation
Reference Answer: Render threads are divided into main threads and Compositor threads. If the CSS animation only changes transform and compositor, The entire CSS animation is executed in the Compositor trhead (JS animation is executed in the Main Thread for the next step). Note that if you change transform and opacity, layout or paint will not be used.
The difference between:
- The function coverage of JS is larger than CSS
- CSS3 is easier than JS, and the performance jump direction is fixed
- Css3 can naturally degrade older browsers that don’t perform well at frame rates
- CSS animations have natural event support
- Css3 has compatibility problems
Let’s talk about block elements and row elements
Reference Answer:
- Block element: Exclusive row and has auto-fill parent element, can set margin and pading, height and width.
- Line elements: Do not monopolize a line, width and height are invalidated, and vertical padding and margin are invalidated.
Ellipsis of text for multi-line elements
display: -webkit-box
-webkit-box-orient:vertical
-webkit-line-clamp:3// Set it to overflow:hidden in the first lineCopy the code
Opacity =hidden, opacity=0, display:none
Reference Answer:
opacity=0
The element is hidden but does not change the page layout, and if the element is already bound to some event, such as the Click event, clicking that area can also trigger the click eventvisibility=hidden
The element is hidden, but does not change the page layout, but does not trigger events that the element is already bound to.display=none
Hiding the element and changing the layout of the page can be interpreted as removing the element from the page.
Double margin overlap problem (margin folding)
Block elements of multiple adjacent (sibling or parent-child) normal streams overlap vertically.
The result of folding is:
- When two adjacent margins are both positive, the result of folding is the larger value between them.
- When two adjacent margins are both negative, the result of folding is the greater value of their absolute values.
- When two margins are positive and negative, the result of folding is the sum of the two.
Comparison of Position attributes
Reference Answer:
Fixed: The element’s position is fixed relative to the browser window, and it does not move even if the window scrolls. Fixed positioning makes the position of the element independent of the document flow and therefore does not take up space. Fixed positioned elements overlap with other elements.
Relative position: If an element is positioned relative to it, it will appear in its position. The element can then be moved “relative” to its starting point by setting its vertical or horizontal position. When relative positioning is used, 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 positioned element relative to the nearest positioned parent or, if the element has no positioned parent, relative to < HTML >. Absolute positioning makes the position of an element independent of the document flow and therefore does not take up space. Absolute Positioned elements overlap with other elements.
Sticky localization: An element is first positioned according to the ordinary document flow, and then positioned relative to the flow root (BFC) and containing block (the nearest block-level ancestor element) of the element in the flow. Element positioning is then represented by relative positioning before crossing a specific threshold, followed by fixed positioning.
Default location Static: the default value. Without positioning, the element appears in the normal stream (ignoring the top, bottom, left, right, or Z-index declarations). Inherit: Specifies that the value of the position property should be inherited from the parent element.
Remove the floating
Reference Answer:
- Use the empty element with the clear attribute
/** Use an empty element after the float element such as
and in the CSS to. Clear {clear:both; } property cleans up the float. Alternatively, use
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>
/** Advantages: simple, less code, good browser compatibility. Cons: Need to add a lot of non-semantic HTML elements, code is not elegant, not easy to maintain later. * /
Copy the code
- Use the OVERFLOW property of CSS
/** Add overflow:hidden to the container of floating elements; Or overflow: auto; You can clear floats, and in IE6 you also need to trigger hasLayout, such as setting the container width or zoom:1 for the parent element. After the overflow property is added, the float element goes back to the container layer and pushes up the container height to clean up the float. * /
.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
- Adding a float attribute to the container of a float element clears internal floats, but this will make it float as a whole, affecting the layout and is not recommended.
- Handle using adjacent elements.
// Do nothing, add the element after the float elementclearProperties..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
- Using CSS :after pseudo-elements
/** Combine: After pseudo-elements (not pseudo-classes, but pseudo-elements that represent the most recent element after an element) with IEhack, which is used to trigger hasLayout, and is perfectly compatible with all major browsers. Add a ClearFix class to the container of floating elements, and then add one to the class :after pseudo-element implementation adds an invisible Block element to the end of the element to clean up the float. * /
.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
Overflow handling in CSS3
< span style = “box-sizing: border-box; Ellipsis represents trimmed text for the display of ellipses; String represents the clipped text using the given string.
Element of float, what is display
Reference Answer: Display is block
A method to hide an element in a page
Reference Answer:
display:none; visibility:hidden; opacity: 0; positionMove to the outside,z-indexCoating cover and so on1. opacity:0The element is hidden but does not change the page layout, and if the element is already bound to some event, such as the Click event, clicking that area can also trigger the click event2. visibility: hidden, the element is hidden, but does not change the page layout, but does not trigger the event that the element is already bound to3. display:none, hides the element, and changes the layout of the page, meaning that the element is removed from the page.Copy the code
Three column layout implementation, write as much as possible, floating layout, three div generation order has no effect
Reference Answer:
- use
Float + margin:
To divFloat: left
Left div adds attributesMargin - right: left
Spacing px from center and adding attributes to right divMargin - left, left
And center plus the spacing. - use
Float + overflow:
To divFloat: left
“, and set the div for rightoverflow:hidden
. This way the two boxes float and the other box triggers the BFC for adaptation. - use
The position:
Parent div SettingsPosition: relative
, three child div SettingsPosition: absolute
The width and interval of the box should be calculated to set the position, which is more compatible. - Use table implementation: parent div Settings
Display: table
To set upBorder - spacing: 10 px
// Set the spacing, optionally, child divdisplay:table-cell
, this method has good compatibility and is suitable for the situation where the height and width are unknown, but the margin fails and the design interval is troublesome. - Flex implements: parent div Settings
Display: flex
; Div Settings for left and Centermargin-right
; Then set the right div to Flex: 1; This way right is adaptive, but Flex compatibility is not good. - Grid implementation: parent div Settings
Display: the grid
To set upgrid-template-columns
Property, fixed first column, second column width, third column auto,
Calc properties
Width: Calc (100%-10px); width: Calc (100%-10px);
Display: What is the difference between table and table itself
The table is the same as the table itself. The CSS declaration of table allows an HTML element and its children to use table-based CSS layouts like the table element, making it easy to define a cell’s boundaries, backgrounds, etc., without the semantic problems associated with tabbed tags like table. The reason why table is gradually eliminated is that the files written by DIV + CSS are smaller than those written by table side, and table must be displayed after the page is fully loaded, while DIV is displayed line by line. Table has too much nesting and is not as concise as DIV.
Z-index locating method
Reference Answer: The z-index attribute sets the stack order of the elements. The elements in a better stack order are placed before the elements in a lower order. The Z-index can be negative, and the Z-index can only work on positioned elements. Its property values are auto, default, stack order equal to the parent element, number, inherit, inherit from the parent element’s z-index property values.
The difference between line-height and height
Line-height refers to the height between the top and bottom lines of a paragraph of text in a layout.
Set the background color of an element. What areas will the background color fill?
Background-color fills the content, padding, and border areas of the element.
Priority of property and pseudo-class selectors
Attribute selectors and pseudo-class selectors have the same priority
The difference between inline-block, inline and block; Why img is inline and can set width and height
Reference Answer:
- A Block is a block-level element that has line breaks before and after it, and can set width, height, and margin/padding in both horizontal and vertical directions.
- Inline: Sets width and height to invalid, margin to invalid on vertical, padding to invalid on horizontal and vertical, and no line breaks before or after
- Inline-block: the width and height can be set. Margin /padding is valid in both horizontal and vertical directions
Create a coin rotation effect with CSS
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 redraw and rearrange, how to reduce redraw and rearrange, what are the ways to get 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:
- Add or remove visible DOM elements,
- Changes to the size position of an element
- The browser page is initialized,
- If the browser window size changes, rearrangement does not necessarily lead to redrawing, redrawing does not necessarily lead to rearrangement,
Methods to reduce redraw rearrangements are:
- Instead of doing DOM queries when layout information changes,
- With CSSText, the className changes the property once
- Using the fragments
- 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 with the syntaxbox-sizing:content-box/border-box/inherit
content-box: The width and height are applied to the content box of the element, respectively. Outside the width and height, the inner margin and border of the element are drawnborder-box: The width and height of the element determine the element's border box.inherit: inherits the parent elementbox-sizing
Copy the code
JavaScript
Error in the length of get request parameters
Myth: We often say that the size of get request parameters is limited, while the size of POST request parameters is unlimited. In fact, the HTTP protocol never specifies a limit on the length of a GET/POST request. The restriction on get request parameters is the source and browser or Web server, which limits the length of the URL. To clarify this concept, we must reiterate the following points:
- The HTTP protocol does not specify length limits for GET and POST.
- The maximum length of GET is displayed because browsers and Web servers limit the length of urIs.
- The maximum length varies from browser to browser and WEB server to WEB server.
- If Internet Explorer is supported, the maximum length is 2083 bytes. If only Chrome is supported, the maximum length is 8182 bytes.
Fill in the cache differences between GET and POST requests
A GET request is similar to a lookup process in that the user retrieves data without having to connect to the database every time, so caching can be used. Unlike Post, which generally does modification and deletion, it must interact with the database, so it cannot use caching. Therefore, GET requests are suitable for request caching.
A little bit about closures
A closure is a function that can read variables inside other functions, or a child function that is called outside the parent function’s scope is not released.
Talk about class creation and inheritance
Reference Answer:
// 1) class creation (es5) : new a function, add properties and methods to the prototype of this function.
// 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);
};
// Create an Animal class with methods and attributes.
// (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; /** new = Animal; /* Cat. Prototype = Animal; Features: Based on the prototype chain, is both a parent class instance, but also a subclass instance disadvantages: can not implement multiple inheritance */
// (3) constructor inheritance: use the parent class constructor to enhance the instance of the child class, which is equivalent to copying the instance attributes of the parent class to the child class.
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: can only inherit the attributes and methods of the parent class instance, cannot inherit the attributes and methods of the prototype.
Instance inheritance: add new features to the parent class instance, return copy inheritance as the child class instance: copy attributes and methods on the parent class element. * /
/** (5) Combinatorial inheritance: equivalent to the combination of construction inheritance and prototype chain inheritance. It inherits the attributes of the parent class and retains the advantages of passing arguments by calling the parent class constructor, and then implements function reuse */ by using the parent class instance as a subclass prototype
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
// Attribute: can inherit instance attributes/methods, also can inherit prototype attributes/methods
// Disadvantages: the parent constructor is called twice, generating two instances
/** (6) Parasitic combination inheritance: by parasitic way, the instance attribute of the parent class is cut off, so that when the constructor of the parent class is called twice, the two instance method/attribute */ is not initialized
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;
// Use the instance as the prototype of the 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
// Is recommended
Copy the code
Talk about the flow of events in the front end
HTML interaction with javascript is event-driven, such as mouse click event onclick, page scroll event onscroll, etc. You can subscribe to events by adding event listeners to documents or elements in documents. To understand when these events are invoked, you need to understand the concept of “event flow.” What is event flow? Event flow describes the order in which events are received from the page. DOM2 event flow consists of the following phases.
- Event capture phase
- In the target stage
- Event bubbling phase
AddEventListener: addEventListener is a dom2-level event addition that specifies an event handler. This method takes three parameters: the name of the event to be processed, the function that acts as the event handler, and a Boolean value. The last Boolean argument, 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 I bubble events first and then catch them
In the DOM standard event model, capture first and bubble later. However, if you want to achieve the effect of bubbling first and then capturing, for the same event, listen to capture and bubbling, corresponding to the corresponding handler function, listen to capture event, first suspend execution, until the bubbling event is captured and then execute 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 ul and LI tag event monitoring, for example, when we add events, we use the event delegation mechanism, not directly added to the LI tag, but added to the UL parent element.
Benefits: Suitable for binding dynamic elements, new child elements can also have listener functions, can also have event triggering mechanism.
Talk about lazy loading and preloading of images
Reference Answer:
- Preloading: Images are loaded ahead of time and rendered directly from the local cache when the user needs to view them.
- Lazy loading: The main purpose of lazy loading is to serve as a front-end optimization for the server, reducing the number of requests or delayed requests.
The essence of two technologies: the behavior of both is opposite, one is early loading, one is slow or even not loading. Lazy loading relieves the pressure on the front end of the server, while preloading increases it.
The difference between mouseover and MouseEnter
Reference Answer:
- Mouseover: Events are triggered when the mouse moves over an element or its child, so there is a repetitive, bubbling process. The corresponding remove event is mouseout.
- Mouseenter: When the mouse removes the element itself (any child element that does not contain the element), it triggers an event that does not bubble. The corresponding remove event is mouseleave.
What does the JS new operator do
The new operator creates an empty object that points to the constructor’s prototype and returns the object after execution.
Change the pointer to this inside a function.
The first argument to apply and call is the same as the object to be changed. The second argument is arg1,arg2, arg1,arg2… In this form. Changing the this scope by bind returns a new function that will not be executed immediately.
JS positions, such as clientHeight scrollHeight, offsetHeight, as well as the scrollTop, offsetTop, what is the difference between clientTop?
Reference Answer:
- ClientHeight: indicates the height of the visible area, excluding the border and scroll bar.
- OffsetHeight: Indicates the height of the visible area, including the border and scroll bar.
- ScrollHeight: Indicates the height of all areas, including those that are hidden because of scrolling.
- ClientTop: Indicates the thickness of the border. If this parameter is not specified, it is usually 0.
- ScrollTop: The height of the object hidden after scrolling relative to the top of the parent coordinate specified by the offsetParent property (the element or body element positioned by CSS).
JS drag function implementation
Reference Answer:
- The first three events are
Mousedown, Mousemove, mouseup
- When the mouse is clicked down, you need a tag to indicate that the mouse has been clicked down. You can perform the specific methods in mousemove.
- ClientX, clientY refers to the coordinates of the mouse, marking abscis and ordinate respectively, and we use offsetX and offsetY to represent the initial coordinates of the element. The example of movement should be: the coordinates when the mouse moves – the coordinates when the mouse is down. That is, the positioning information is: the coordinate when the mouse is moved – the coordinate when the mouse is down + the element’s initial offetLeft. There is another thing that is also rational, that is, drag and drop is absolute positioning at the same time, we change the left and under the condition of absolute positioning
The value of top. Add: This can also be done via HTML5 Drag and drop.
Asynchronous loading of JS methods
Reference Answer:
- If your script does not change the content of the document, add the defer attribute to
<script>
Tag to speed up processing of documents. Because the browser knows that it will be able to safely read the rest of the document without executing the script, it will delay the interpretation of the script until the document has been displayed to the user. - The async, HTML5 attribute only applies to external scripts, and if in IE both defer and Async exist, defer takes precedence and the script executes when the page is complete. Create a script tag and insert it into the DOM.
Ajax solves browser caching problems
Reference Answer:
- Before ajax sends the request
anyAjaxObj.setRequestHeader("If-Modified-Since","0")
. - Before ajax sends the request
anyAjaxObj.setRequestHeader("Cache-Control","no-cache")
. - Add a random number after the URL:
"fresh=" + Math.random()
. - Add a time rub after the URL:
"nowtime=" + new Date().getTime()
. - If you are using jQuery, you can do this directly
$.ajaxSetup({cache:false})
. So that all ajax on the page will execute this statement without needing to save the cache record.
JS throttling and anti – shake
Reference Answer:
Debouncing: The technique is to combine sequenced invocations into one, that is, the number of events that are fired within a certain 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 the scroll
}, 250);
// Bind 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 triggering interval is reached, the handler is triggered
if(curTime - startTime >= mustRun){
func.apply(context,args);
startTime = curTime;
// Reset the timer if the trigger interval is not reached
}else{
timeout = setTimeout(func, wait); }}; };// The handler that you actually 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
Garbage collection mechanism in JS
The JS garbage collection mechanism is simple: find variables that are no longer in use, and free their memory. There are two ways to implement this: tag 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 clean up of memory is complete and the memory they occupy is reclaimed.
Reference counting: Reference counting is a less common garbage collection strategy. The meaning of reference counting is to keep track of how many times each value is referenced. When a reference type value is assigned to a variable, the number of references to that value is 1. If the same value is assigned to another variable, the number of references to the value is increased by one. Conversely, if a variable containing a reference to that value obtains another value, the number of references to that value is reduced by one. When the number of references to a value becomes zero, there is no way to access the value, and the value has no reason to exist, so it is released.
What does Eval do
Its function is to parse the corresponding string into JS and execute it. JS should be avoided because of the high performance (2 times, once parsed into JS and once executed).
How to understand front-end modularity
Reference Answer: Front-end modularization is a complex file programming a separate module, such as JS files, etc., divided into separate modules for reuse (reuse) and maintenance (version iteration), which leads to the problem of interdependence between modules, so there are commonJS specifications, AMD, CMD specifications, etc., And webpack, a tool for JS packaging (compilation, etc.)
Talk about CommonJS, AMD and CMD
A module is a file that can realize a specific function. With a module, you can easily use other people’s code and load any module you want. CommonJS: Starts with server-side modularity, synchronously defines modularity, each module is a separate scope, module exports, modules.exports, module loads require() imports modules. AMD: Chinese name for asynchronous module definition. RequireJS implements the AMD specification to address the following two issues.
- Multiple files have dependencies, and the dependent file needs to be loaded into the browser before the dependent file
- The browser stops page rendering when it loads, and the more files it loads, the longer the page goes 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 the global variable used to define the module:define(id? dependencies? ,factory)// Use the module loading function on the page:
require((dependencies), factory);Copy the code
The require () function is asynchronously loaded when loading dependent functions, so that the browser does not lose response, and the callback function it specifies will only be executed if the previous module is successfully loaded. Because web pages stop rendering when loading JS, we can load JS asynchronously, and if we need to rely on something, we can also rely on it asynchronously, 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 different from an object, so we start with a few types to decide whether newObj is an object or an array.
Implement a once function that passes in function arguments only 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 a promise
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 object properties to change
// Suppose we have a user object here,
// (1) In ES5, you can use Object.defineProperty to listen on existing attributes
Object.defineProperty(user,'name', {set:function(key,value){}})// Disadvantages: If the ID is not in the user object, you cannot listen for changes in the ID
// (2) In ES6, you can use Proxy to do this
var user = new Proxy({}, {set:function(target,key,value,receiver){}})// If an attribute does not exist in user, the user. Id definition can also be used to listen for changes in the attribute.
Copy the code
How to implement a private variable that can be accessed using getName but not directly
// (1) defineProperty
obj={
name:yuxiaoliang,
getName:function(){
return this.name
}
}
object.defineProperty(obj,"name", {// Not enumerable Not configurable
});
// (2) by creating a function
function product(){
var name='yuxiaoliang';
this.getName=function(){
returnname; }}var obj=new product();
Copy the code
== and ===, 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
// (relative improvement over === and ==)
Copy the code
The difference between setTimeout, setInterval and requestAnimationFrame
Unlike setTimeout and setInterval, requestAnimationFrame does not require a time interval. Most computer monitors refresh at 60Hz, which equates to about 60 redraws per second. Most browsers limit redrawing to the frequency at which the display can be redrawn, because beyond that the user experience will not improve. Therefore, the optimal loop interval for the smoothest animation is 1000ms/60, which is approximately 16.6ms. RAF uses the system time interval, which will not affect RAF because of the previous tasks. However, if there are too many previous tasks, it will respond to the time interval when setTimeout and setInterval are actually running.
Features:
- RequestAnimationFrame brings together all DOM operations in each frame in a single redraw or reflow, and the redraw or reflow interval closely tracks the browser refresh rate.
- RequestAnimationFrame will not be redrawn or reflow in hidden or invisible elements, which of course means less CPU, GPU, and memory usage
- RequestAnimationFrame is a browser-specific API for animation that optimizes method calls at runtime and pauses animation automatically 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:
// This is implemented using the apply or call methods.
// (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 consider? When you bind a new function, you must inherit the original function's prototype
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
How does JS control loading one image at a time and then loading the next
Reference Answer:
// (1
<script type="text/javascript">
var obj=new Image();
obj.src="http://www.phpernote.com/uploadfiles/editor/201107240502201179.jpg";
obj.onload=function(){
alert('Image width 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)
<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('Image width 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 data type
Reference Answer:
Basic data type: Undefined, Null, Boolean, Number, String, Symbol reference data type: Object
JS judgment type
Reference answer: judgment method: typeof (), instanceof, Object. The prototype. ToString. Call (), constructor and etc
Array to heavy
Reference Answer:
- IndexOf loops for de-weighting
- ES6 Set deweighting; Array.from(new Set(array))
- Object key value pairs are de-duplicated. Object[value1] = true. If Object[value2] is present in another value, 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 a collection of local variables of a function that continue to exist after the function returns. A closure is a function’s “stack” that is not released when the function returns, and we can also understand that these function stacks are allocated not on the stack but on the heap. Closures are generated when you define another function within a function.
(2) Why to use:
Anonymous self-executing functions: We know that all variables are added to the attributes of the global object by default if the var keyword is not added. Such temporary variables can be added to the attributes of the global object. This makes the global object too large, affecting access speed (because variable values need to be traversed through the prototype chain). In addition to using the var keyword every time a variable is used, we often encounter situations where a function only needs to be executed once and its internal variables do not need to be maintained and can be closed. Result cache: We will encounter a lot of development situation, suppose we have a process is very time consuming function object, each invocation will take a long time, so we need to calculate the value of the stored, when 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 found value. Closures do just that, because they do not free external references so that the values inside the function can be preserved. Encapsulation: implement classes, inheritance, etc.
Can you talk about the language features of JS
Reference Answer:
- Run on the client browser;
- No precompilation, directly parsing the execution code;
- Is a weakly typed language, more flexible;
- Operating system independent, cross-platform language;
- Scripting languages, interpreted languages
JS implementation across domains
JSONP: Cross-domain communication is achieved by dynamically creating a script and then requesting a reference url. Document.domain + iframe cross-domain: both pages are co-domain by js forcing document.domain to be the base primary domain. Location. hash + iframe Cross-domain: A wants to communicate with B across domains through the middle page C. Three pages, different fields use iframe location.hash to transfer values, the same fields directly js access to communicate. Window. name + iframe Cross-domain: The SRC attribute of iframe is used to transfer the cross-domain data from the outdomain to the local region. That is, the window.name of iframe is used to transfer the cross-domain data from the outdomain to the local region.
PostMessage cross-domain: One of the Window properties that can operate across domains.
CORS: Set access-Control-allow-origin on the server. The front end does not need to be set. If you want to bring cookies, please ask. Proxy cross-domain: Start a proxy server to forward data
Rearrange and redraw. Talk about that
Redraw: When the box position, size, and other properties, such as color and font size, have been determined, the browser repaints the original colors and renders the content on the page. Redraw refers to the behavior of the browser triggered by a change in the appearance of an element. The browser redraws the element based on its new attributes to give it a new appearance.
Conditions that trigger a redraw: changes the appearance attributes of an element. Color = background-color
Note: Table and its internal elements may require multiple computations to determine the attribute values of its nodes in the rendered tree, which takes twice as long as the equivalent element. This is one of the reasons we try to avoid using tables to lay out our pages.
Rearrangement (refactoring /reflow /reflow) : When part (or all) of the render tree needs to be rebuilt due to changes in the size, layout, hiding, etc., this is called reflow. Each page needs to be refluxed at least once, the first time the page loads.
The relationship between redraw and rearrangement: During backflow, the browser inactivates the affected part of the render tree and reconstructs that part of the render tree. After backflow, the browser redraws the affected part of the render tree to the screen. This process is called redraw. So rearrangement must lead to redrawing, but redrawing does not necessarily lead to rearrangement.
The use of promise + Generator + Async
Reference Answer: Promise solved problem: Callback hell Promise specification:
- Promise has three states, including pending, completed /resolved and rejected. The state of promise can only be changed from “waiting” to “completed” or “rejected” rather than reversed. At the same time, “completed” and “rejected” cannot be switched to each other.
- A promise must provide a THEN method to access its current value, final value, and reason. Promise.then (resolve,reject),resolve, and reject are optional arguments. If resolve or reject are not functions, they must be ignored. The then method must return a Promise object.
/ * * use: Instantiating a Promise object requires passing in the functions (with two arguments),resolve and reject, to internally determine the state. The resolve and reject functions pass in arguments that can be used in callbacks The callback function receives. */
var promise = new Promise(function(resolve, reject) {
setTimeout(function(){
resolve('Ok, ha, ha, ha.');
});
});
promise.then(function(val){
console.log(val)
})
// Then receives two functions, corresponding to callbacks to the resolve and reject states, which receive arguments passed in during instantiation.
promise.then(val= >{
//resolved
},reason= >{
//rejected
})
If a rejection is thrown at a then, an error is thrown at a catch, and a rejection is thrown at it and a catch is not thrown at it. In addition, errors that occur in the callback function in then will only be caught in the next level of THEN and will not affect the state of that 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 example
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 is also used
});
// The two are not equivalent:
// At this point, catch does not catch p1 error, but P2 error,
p1().then(res= >{
return p2()// P2 returns a Promise object
}).catch(err= > console.log(err))
/** An error catch error use case: If an error occurs, the call to this function will still enter the resolve callback in then, because the catch was already called when the promise object was instantiated in p1. If an error occurs, it will enter the catch and return a new one Promise, so the resolve callback in p1's then chain will be entered even if an error occurs.*/
function p1(val){
return new Promise((resolve,reject) = >{
if(val){
var len = val.length;// An error occurs when passing null
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 return and throw in callback functions, so then can return a Promise or other value, or throw an error object, but if there is no return, undefined will be returned by default. The subsequent then callback argument 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, which results in an error
})
.then(function(data2){
return p2(data2+1)
})
.then(res= >console.log(res))
Copy the code
The Generator function:
Generator functions use:
- Section execution, can be paused
- You can control the phases and the return values for each phase
- You can tell 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: Using the pause effect of generator functions, you can write asynchronous operations in yield statements and execute them later when the next method is called. This is essentially equivalent to not having to write the callback function, because subsequent operations of the asynchronous operation can be put under the yield statement until the next method is called anyway. Therefore, an important practical use of Generator functions is to handle asynchronous operations and override callback functions.
Async and async: async means that this is an async function and await can only be used inside the function. Await means to await the result of an asynchronous operation before continuing. Await is typically followed by an example promise object :async is used to define an asynchronous function that returns a promise. If async returns a synchronized value, the value is wrapped as a Promise to 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 features of arrow functions
The difference between arrow functions and normal functions is that:
- Arrow functions don’t have this, so we need to find the value of this by looking up the scope chain, which means that if the arrow function is contained by a non-arrow function, this is bound to the nearest non-arrow function’s this,
- The arrow function does not have its own arguments object, but can access the arguments object of the peripheral function
- It cannot be called by the new keyword, nor does it have a new. Target value or prototype
JS loading process is blocked.
Reference answer: Specify async properties for script tags. If async=”async”, the script executes asynchronously relative to the rest of the page (the script will be executed while the page continues parsing) if async is not used and defer=”defer” : the script will execute when the page is finished parsing
Server-side programming /Ajax
The disadvantage of the json
- JSON only supports GET, because script tags can only use GET requests;
- JSONP requires backend coordination to return data in the specified format.
Cross-domain (JSONP, Ajax)
Json: Ajax requests are affected by the same origin policy, which does not allow cross-domain requests. However, the link in the SRC attribute of the script tag can access cross-domain JS scripts. With this feature, the server no longer returns JSON data, but returns a piece of JS code that calls a function, which is called in SRC. This is cross-domain.
How is cross-domain implemented
- JSONP: Cross-domain communication is achieved by dynamically creating a script and then requesting a reference url. Document.domain +iframe cross-domain: both pages are co-domain by js forcing document.domain to be the base primary domain. Location. hash + iframe Cross-domain: A wants to communicate with B across domains through the middle page C. Three pages, different fields use iframe location.hash to transfer values, the same fields directly js access to communicate. Window. name + iframe Cross-domain: The SRC attribute of iframe is used to transfer the cross-domain data from the outdomain to the local region. That is, the window.name of iframe is used to transfer the cross-domain data from the outdomain to the local region.
- PostMessage cross-domain: One of the Window properties that can operate across domains.
- CORS: Set access-Control-allow-origin on the server. This parameter is not required on the front end. If cookie requests are required, set access-Control-allow-origin on the front end.
- Proxy cross-domain: a proxy server is created to forward data
Implementing an Ajax
AJAX creates asynchronous objects XMLHttpRequest manipulates XMLHttpRequest objects
- Set the request parameters (how the request is made, the relative path of the requested page, whether it is asynchronous)
- Set the callback function, a function that handles the server response, using onreadyStatechange, similar to a function pointer
- Gets the readyState property of the asynchronous object: this property holds the status information of the server response. The onReadyStatechange function is executed whenever readyState changes.
- Check the status of the response packet. If the value is 200, the server runs normally and returns the response data.
- Read the response data, which is returned by the server via the responseText property.
var xhr = new XMLHttpRequest();
xhr.open('get'.'aabb.php'.true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState==4) {
if(xhr.status==200) {
console.log(xhr.responseText); }}}Copy the code
Mobile Web Development
Know the PWA?
PWA stands for Progressive Web App, or Progressive Web application. A PWA application is first and foremost a Web page, and a Web application can be written using Web technology. Then add App Manifest and Service Worker to realize PWA installation and offline functions
Mobile layout scheme
Give you a direct link to super detailed. Juejin. Im/post / 599970…
Rem, Em
How rem units are converted to pixel values When rem units are used, the page’s conversion to pixel size depends on the font size of the leaf root element, that is, the HTML element. The font size of the root element is multiplied by the rem value. For example, if the font size of the root element is 16px, 10rem is the same as 10*16=160px.
When using EM units, the pixel value is the em value multiplied by the font size of the element using EM units. For example, if a div font is 18px, set its width and height to 10em, then the width and height will be 18px*10em=180px.
.test{
width: 10em;
height: 10em;
background-color: #ff7d42;
font-size: 18px;
}
/** Keep in mind that em changes based on the font size of the element that uses it, not the font size of the parent element. Some elements are several times the size of the parent element because they inherit the font size from the parent element. * /
Copy the code
With em unit inheritance, each element automatically inherits its parent element’s font size, and inherited effects can only be overridden by explicit font units, such as PX and vw. Font size = em; fontsize = em; fontsize = em; fontsize = em;
Elements in the root HTML will inherit the font size set in the browser unless explicitly fixed values are set to override. So while the font size of an HTML element is directly determined by rem, the font size is first and foremost derived from the browser Settings. (So be sure to set the size of the HTML value because users may have different browser font sizes.)
When the EM unit is set on an HTML element it is converted to the EM value multiplied by the browser font size setting.
html{
font-size: 1.5 em;
}
/** you can see that the browser default fontsize is 16px, so when setting the HTML fontsize to 1.5em, the corresponding px value is 16*1.5=24px, so when setting the rem value of other elements, the corresponding pixel value is n*24px. For example, the rem value of test is 10, */
.test{
width: 10rem;
height: 10rem;
background-color: #ff7d42;
}
/** Summary: 1. The translation of rem units into pixel values is determined by the font size of HTML elements. This font size is affected by the font size Settings in the browser, unless the HTML explicitly overwrites a unit for font size. 2. Em units are converted to pixel values depending on the font size of the element that uses them, but can be complicated by inheritance. Advantages and disadvantages of em can let our page more flexible, more robust, than write die px value everywhere, em seems more tension, change the parent element's font size, child elements will ratio changed, this change seems to predict the infinite possibility, the disadvantage of em do elastic layout is also extremely important, once a node change the font size, Then all descendants must be recalculated
Copy the code
Mobile adaption 1px problem
Recommend blog.csdn.net/weixin_4367…
- Write px values as decimals (not recommended)
-webkit-min-device-pixel-ratio, -webkit-min-device-pixel-ratio, -webkit-min-device-pixel-ratio CSS can be written like this // with the -webkit-min-device-pixel-ratio setting..border { border: 1px solid # 999 }
@media screen and (-webkit-min-device-pixel-ratio: 2) {
.border { border: 0.5 px. solid # 999}}@media screen and (-webkit-min-device-pixel-ratio: 3) {
.border { border: 0.333333 px. solid # 999}} // If less/sass is used, it is just added1Mixin // Cons: Android and lower versions of IOS do not work, this may be the future standard, not count on it nowCopy the code
- flexible.js
This is taobao mobile terminal, the plan of the lot address: https://github.com/amfe/lib-flexible. If you can set the viewPort width to the actual physical width of the device,
When flexible. Js detects an IOS model, it calculates scale = 1/devicePixelRatio and sets viewPort
- Pseudo-class +transform implementation
/** I personally think the perfect solution to the 1px border problem is pseudo-class +transform. Principle: remove the border of the original element, then use :before or :after to redo the border, and reduce the scale of the transform by half. The original element is positioned relative to the original element, and the new border is absolutely positioned. With media Query, responsive layouts can be achieved by writing different styles for devices with different resolutions, such as setting different background images for screens with different resolutions. For example, set @2x map for small screen mobile phone, set @3x map for large screen mobile phone, through media query can be very convenient to achieve. But the downside of media queries is that if there are too many styles that need to be changed as the browser sizes change, then multiple sets of style code can be cumbersome. * /
@media screen and (min-width: 320px) {
html {
font-size: 50px; }}@media/** Convenient application is widely applicable to PC mobile pages, usually do adaptive layout we are more commonly used. Disadvantages: relative to the code to repeat a lot, you have to know the width of the device, the resolution of the phone is a lot of trouble, but the performance must be the highest; There may be a flash screen problem. @Media deals with the interface compatibility problem between mobile phone and PC, and the access problem occurs on IE. Baidu search for two methods, one is response.js, and the other is CSS3-mediaquerieshttp://blog.csdn.net/small_tu/article/details/47317453* /Copy the code
Experience in mobile performance optimization
Give you a reference to a list of mobile terminal performance optimization methods
Mobile Compatibility
Other reference link: https://zhuanlan.zhihu.com/p/28206065
Gesture events
Gesture events | The event, |
---|---|
touchstart | Trigger when a finger touches the screen instead of a click event to trigger a mobile click event |
touchmove | Trigger instead of scroll event when finger touches screen |
touchend | Trigger when the finger leaves the screen instead of the click event to trigger the mobile click event |
Figure 2X figure 3X figure fit
In actual program development, the value used in our code refers to the logical resolution pt, not the pixel resolution px. For example, if we define the height of a button as 45, the 45 refers to 45pt, not 45px. 1pt = 1px on non-Retina display, 1pt = 2px on 4 and 4.7-inch Retina display, 1pt = 3px on 5.5 and X display. For example, @1x is 22px, @2x is 44px and @3x is 66px, and they are named image.png respectively. Create a New image Set in the Assets. Xcassets of the project and change the name to image. And drag and drop the corresponding size of the picture to the corresponding position.
/* According to DPR display 2x figure /3x figure */
.bg-image(@url) {background-image: ~"url('@{url}@2x.png')";
@media (-webkit-min-device-pixel-ratio: 3), (min-device-pixel-ratio: 3) {background-image: ~"url('@{url}@3x.png')"; }}.bg-color(@color) {
background-color: @color;
}
Copy the code
The image is on Android and some of the devices are blurry
This problem is caused by the difference in devicePixelRatio, because the resolution of mobile phones is too small. If the web page is displayed according to the resolution, the words will be very small. All Apple systems changed the resolution of iPhone 4 from 960×640 pixels to 480×320 pixels in the web page. So devicePixelRatio = 2. Android devicePixelRatio is messy, with values of 1.5, 2 and 3. In order to display pictures more clearly in the phone, The img tag must contain an image twice the width and height of the img tag. For example: a div is 100×100 and its background must contain 200×200. Set background-size:contain to contain any other image that contains it.
Prevents pages from zooming in and out on the phone
<meta name="viewport" content="user-scalable=no">
<meta name="viewport" content="initial-scale=1,maximum-scale=1">
Copy the code
Transiton splash screen
// Set the inline element in3How is D space presented: reserved3D-webkit-transform-style:preserve-3D; // Sets whether the back of the converted element is visible to the user: hide -webkit-backface-visibility:hidden;
Copy the code
Dragging the scroll bar up and down is slow and slow
body {
-webkit-overflow-scrolling: touch;
overflow-scrolling:touch;
}
Copy the code
Hold down the page for a long time
element{
-webkit-touch-callout: none;
}
Copy the code
Front-end engineering
How does Babel work?
Babel’s translation process is divided into three stages:
- Parse: Parsing code to generate an abstract syntax tree (AST), a process of lexical analysis and parsing
- Transform Transform: Perform a series of operations on the AST. Babel receives the AST and traverses it with babel-traverse, adding, updating, and removing operations.
- Generate Generate: Convert the transformed AST into JS code using the module babel-generator
How to write a Babel plug-in?
Babel parses into an AST, and then the plug-in changes the AST, and then Babel outputs the code so Babel’s plug-in module requires you to expose a function that returns a visitor within that function
module.export = function(babel){
return {
visitor: {}}}Copy the code
Visitor is where the various types of AST nodes are processed, so how do we know what nodes Babel generates in the AST? Very simple, you can print the result of Babel conversion, or there is a portal here :AST Explorer
Const result = 1 + 1; const result = 1 + 2; const result = 1 + 2
var babel = require('babel-core');
var t = require('babel-types');
const visitor = {
BinaryExpression(path) {
const node = path.node;
let result;
// Check whether both sides of the expression are numbers
if (t.isNumericLiteral(node.left) && t.isNumericLiteral(node.right)) {
// Operate according to different operators
switch (node.operator) {
case "+":
result = node.left.value + node.right.value;
break
case "-":
result = node.left.value - node.right.value;
break;
case "*":
result = node.left.value * node.right.value;
break;
case "/":
result = node.left.value / node.right.value;
break;
case "* *":
let i = node.right.value;
while (--i) {
result = result || node.left.value;
result = result * node.left.value;
}
break;
default:}}// If the above operation has any result
if(result ! = =undefined) {
// Replace the expression node with the number literalpath.replaceWith(t.numericLiteral(result)); }}};module.exports = function (babel) {
return {
visitor
};
}
// The plugin is ready, let's run the plugin to try
const babel = require("babel-core");
const result = babel.transform("const result = 1 + 2;", {plugins: [require("./index")]});console.log(result.code); // const result = 3;
Const result = 1 + 2 + 3 + 4 + 5; ? Const result = 3 + 3 + 4 + 5; So that's kind of weird. Why don't we just do 1 plus 2, and then we don't go any further? If we look at the AST tree of this expression you can see that Babel parses into expressions and then nested expressions inside. Expression (expression (expression (expression ((1 + 2) + 3) + 4) + 5)) and our judgment condition does not match all, only match 1 + 2 */
// Check whether both sides of the expression are numbers
if (t.isNumericLiteral(node.left) && t.isNumericLiteral(node.right)) {}
/** if ((3 + 3) + (4) + (5)) + (3 + 3) + (5)) + (3 + 3) + (5)) + (3 + 3)) Expression (expression (6 + 4) + 5) expression (10 + 5) 15 */
// If the above operation has any result
if(result ! = =undefined) {
// Replace the expression node with the number literal
path.replaceWith(t.numericLiteral(result));
let parentPath = path.parentPath;
// Traverses the parent node up
parentPath && visitor.BinaryExpression.call(this, parentPath);
}
/** const result = 15; What about the other operations: */
const result = 100 + 10 - 50>>>const result = 60;
const result = (100 / 2) + 50>>>const result = 100;
const result = (((100 / 2) + 50 * 2) / 50) * *2>>>const result = 9;
Copy the code
What is your Git workflow like?
Reference answer: give yourself drainage can refer to my reprint of the political cloud of a very detailed point here jump
Webpack vs. GulP (modularity vs. stream)
- Webpack is a front-end modular solution, which focuses more on module packaging. We can treat all resources in development (pictures, JS files, CSS files, etc.) as modules, process the resources through loader and plugins, and package them into front-end resources that meet the deployment of production environment.
- Gulp emphasizes the workflow of front-end development. We can configure a series of tasks, define the transactions that the tasks handle (such as file compression merging, Sprite graphics, server startup, version control, etc.), and then define the execution sequence so that gulP can execute these tasks, thus building the whole front-end development process of a project.
Vue
Talk about your understanding of VUE
Vue is an incremental framework for building data-driven data with the goal of responding to data binding and view updates through apis. Advantages:
- The data-driven view abstracts the real DOM from the virtual DOM (essentially a JS object), and updates the DOM at the least cost with diff algorithm, responsive and observer, asynchronous queue and other means to render the page.
- Componentization, component code is organized in a single file, making it possible to write HTML \ CSS (scoped CSS isolation) \js in a single file and support more powerful preprocessors with vie-loader.
- Due to the use of virtual DOM, let Vue SSR congenital enough, powerful and rich API to provide a series of API can meet various needs in business development.
- The lifecycle hook function, optional code organization, is pretty smooth when written, but there is still room for optimization (Vue3 composition-API)
Disadvantages:
- Because the underlying responsibility is based on Object.defineProperty (Vue3.0 uses New Proxy()), the API itself does not support IE8 and below
- Innate deficiency of CSR, first screen performance problem (white screen)
- Due to baidu and other search engine crawlers can not crawl js content, spa innate seo optimization heart has insufficient power (Google’s Puppeteer is quite awesome, the implementation of pre-rendering bottom layer is also used in this tool)
What is the virtual DOM?
Virtual DOM is relative to the real DOM rendered by the browser. Before react, Vue and other technologies appeared, we could only change the content displayed on the page by traversing the DOM tree to find the DOM to be modified, and then modify the style, behavior or structure to update the UI. This method consumes quite a lot of computing resources, because every time you query the DOM, you almost need to traverse the whole DOM tree. If you build a virtual DOM object (JS object) corresponding to the DOM tree, and represent the DOM tree in the way of object nesting, then every change in the DOM becomes the change in the properties of the JS object. This allows you to find property changes in js objects with less performance overhead than querying dom trees.
Vue life cycle
How does VUE listen for keyboard events?
/ / @ keyup. Methods
<template>
<input ref="myInput" type="text" value="hello world" autofocus
@keyup.enter="handleKey">
</template>
<script>
export default {
methods: {
handleKey(e) {
console.log(e)
}
}
}
</script>
// addEventListener
<script>
export default {
mounted() {
document.addEventListener('keyup'.this.handleKey)
},
beforeDestroy() {
document.removeEventListener('keyup'.this.handleKey)
},
methods: {
handleKey(e) {
console.log(e)
}
}
}
</script>
<script>
export default {
mounted() {
document.addEventListener('keyup'.this.handleKey)
},
beforeDestroy() {
document.removeEventListener('keyup'.this.handleKey)
},
methods: {
handleKey(e) {
console.log(e)
}
}
}
</script>
Copy the code
How does watch monitor object changes deeply
Deep set totrueYou can listen for changes in the objectlet vm=new Vue({
el:"#first".data: {msg: {name:'Beijing'}},
watch: {msg:{
handler (newMsg,oldMsg){
console.log(newMsg);
},
immediate:true.deep:true}}})Copy the code
What is the difference between delete and vue. delete when deleting an array?
- Delete: only the members of the deleted array are changed to empty/undefined, and other elements’ keys remain unchanged
- Vue. Delete: Deletes the array member directly and changes the array’s key value. (The object is reactive, so make sure the deletion triggers an update to the view.
What is the difference between a watch and a calculated property?
Generally speaking, computed is recommended for functions that can be implemented with both computed and watch monitoring, but the focus is on the caching function of computed
Computed attributes are used declaratively to show that a value depends on other values, and that computed attributes change when the dependent value or variable changes.
Watch listens to variables already defined in data, and when that variable changes, methods in Watch are triggered.
Vue bidirectional binding principle
Vue data bidirectional binding is implemented through data hijacking combined with the publisher-subscriber pattern. The object.defineProperty () method was used to redefine the Object to get and set property values.
Vue3.0 adopted new Proxy () can refer to https://juejin.cn/post/6950826293923414047, the Denver nuggets signed written by the great spirit.
How do you use Axios? How to solve cross-domain problems?
NPM install AXIOS –save can be used, please include get, POST, PUT, patch,delete and other five request methods. You can add access-Control-Allow-Origin in the request header, or change the proxyTable configuration in the index.js file to solve cross-domain problems.
How do I introduce third-party libraries (such as jQuery) into my Vue project?
// 1
// Add script to index.html
<script src=". / static/jquery - 1.12.4. Js. ""></script>
// Then configure external in Webpack
externals: { 'jquery': 'jQuery' }
// Import when used in components
import $ from 'jquery'
// 2. Configure alias in webpack
resolve: { extensions: ['.js'.'.vue'.'.json'].alias: { The '@': resolve('src'), 'jquery':
resolve('the static/jquery - 1.12.4. Js)}}// Then import in the component
// 3. Configure plugins in webpack
plugins: [ new webpack.ProvidePlugin({ $: 'jquery'})]// This is used globally, but will generate an error if eslint is used, so you need to add /*eslint-disable*/ to remove eslint checks before code that uses $.
Copy the code
Why is the Proxy API used instead of defineProperty API in Vue3.0?
Responsive optimization.
- The biggest reason why the defineProperty API is limited is that it can only listen for singleton attributes. The reactive implementation in Vue2. X is based on defineProperty descriptor, which traverses and recurses attributes in data, setting getters and setters for each attribute. This is why a Vue can only respond to predefined attributes in data. It is not possible to use subscripts to directly modify the value of a property or add a non-existent object property in a Vue. This is a limitation of defineProperty.
- The Proxy API listens on an object, so all operations on that object go into the listening operation, which can completely Proxy all properties, resulting in significant performance improvements and better code. Proxy can be understood as a layer of “interception” before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access.
- In Vue. Js 2.x, for an Object with a deep nesting of attributes, to hijack the deep changes within it, you need to recursively traverse the Object, executing Object.defineProperty to make each layer of Object data reactive, which can be a significant performance drain. In vue.js 3.0, the use of Proxy API can not listen to the object’s internal deep attribute changes, so it is processed in the getter to recursive response, such advantage is really access to the internal attribute will become responsive, simple can be said to be on-demand response, reduce performance consumption.
Basic usage:
let datas = {
num:0
}
let proxy = new Proxy(datas,{
get(target,property){
return target[property]
},
set(target,property,value){
target[property] += value
}
})
Copy the code
What optimizations have been made for Vue3.0 compilation?
- Generate Block tree
The granularity of Vue. Js 2.x data updates that trigger rerendering is component-level, with the entire VNode tree traversed within a single component. In 2.0, rendering efficiency is positively correlated with component size: the larger the component, the slower the rendering efficiency. In addition, for some static nodes, and no data update, these traversals are a waste of performance. Vue.js 3.0 does the analysis of static templates in the compilation stage and generates Block trees. Block Tree is a nested Block that cuts the template based on dynamic node instructions. The node structure inside each Block is fixed, and each Block only needs to track the dynamic nodes it contains. So, in 3.0, rendering efficiency is no longer positively correlated with template size, but with the number of dynamic nodes in the template.
- Slot compilation optimization
In vue.js 2.x, if a component passes in slot, the child component will be forced to update every time the parent component updates, resulting in wasted performance.
Vue.js 3.0 optimizes slot generation so that updates to properties in non-dynamic slots only trigger updates to child components. Dynamic slot refers to the operation of using V-if, V-for, and dynamic slot name on a slot that causes the slot to change dynamically at runtime but fails to track the component.
3. Diff algorithm optimization
The virtual DOM in Vue2. X is used for full comparison. In Vue3.0, static flag is added: when comparing with the last virtual node, the value of PatchFlag is compared with the node with patch flag, and the specific content of the current node to be compared can be learned through the information of flag.
- hoistStatic Static promotion
Vue2. X: The element is recreated each time whether or not it participates in the update. Vue3.0: Elements that do not participate in the update are created only once and then reused repeatedly with each rendering.
- CacheHandlers Event listener cache
By default, onClick is treated as a dynamic binding, so it is tracked every time it changes, but because it is the same function, it is not tracked and can be cached and reused.
Tell me about the proxy
Vue’s data hijacking has two disadvantages:
- Cannot listen for changes in the value of an array modified by index
- Unable to listen for changes in the value of object
Proxy is a new API released in ES6 to compensate for both of these shortcomings, so the vue3.x version uses proxy instead of Object.defineProperty.
React
Redux middleware
The middleware provides the mode of third-party plug-ins to customize the process of intercepting action -> Reducer. Change to Action -> middlewares -> Reducer. This mechanism allows us to change the data flow to implement functions such as asynchronous actions, action filtering, logging, exception reporting, and so on.
Common middleware: Redux-Logger: provides log output; Redux-thunk: handles asynchronous operations; Redux-promise: handle asynchronous operations; The return value of actionCreator is promise
React component partition Business component Technical component?
Components are usually divided into UI components and container components based on their responsibilities. The UI component is responsible for rendering the UI, and the container component is responsible for managing the data and logic. The two are connected through the React-Redux method that provides connect.
React Life cycle function
// 1. Initialization phase
getDefaultProps: Gets the default properties of the instancegetInitialStateComponentWillMount: The component is about to be loaded and rendered onto the pagerenderThis is where the component generates virtual DOM nodescomponentDidMountAfter the component is actually loaded// 2. Running status
componentWillReceiveProps: called when the component is about to receive a propertyshouldComponentUpdate: when the component receives a new property or state (can be returnedfalseRender function will not be executed after receiving data without updating the render call.componentWillUpdate: The component is about to update. Properties and state cannot be modifiedrender: Component repaintingcomponentDidUpdate: The component has been updated// 3. Destruction stage:
componentWillUnmount: Component is about to be destroyedCopy the code
React performance optimization is what periodic function?
ShouldComponentUpdate is used to determine if the DOM needs to be repainted by calling the Render method. Because the dom description is very performance consuming, if we can write a more optimized DOM diff algorithm in shouldComponentUpdate method, it can greatly improve the performance.
React performance optimization solution
- Override shouldComponentUpdate to avoid unnecessary DOM manipulation.
- Use the Production version of React. Js.
- Use keys to help React recognize minimal changes to all the child components in the list
Brief introduction to flux idea
The biggest feature of Flux is the “one-way flow” of data.
- User access to View
- The View emits the user’s Action
- Dispatcher receives Action requesting Store to update accordingly
- After Store updates, issue a “change” event
- View updates the page after receiving the “change” event
Understand shouldComponentUpdate?
The React virtual DOM technology requires constant diff comparisons between the DOM and the virtual DOM. If the DOM tree ratio is large, this can be time-consuming. Therefore, React provides shouldComponentUpdate. If we don’t want a component to refresh, or if we don’t want a component to refresh, we can use this function to tell React directly, eliminating the diff operation and further improving efficiency.
React works
React creates a virtual DOM. When a component’s state changes, React first flags the change in the virtual DOM with the “Diffing” algorithm. The second step is reconciliation, which updates the DOM with the results of diff.
What are the advantages of React
- It’s easy to see how a component is rendered simply by looking at the Render function.
- The introduction of JSX makes component code more readable and makes it easier to see how components are laid out or how they refer to each other.
- Support for server-side rendering, which can improve SEO and performance.
What’s the difference between a Class component and a Functional component
- Class components not only allow you to use additional functionality, such as the component’s own state and lifecycle hooks, but also give the component direct access to the Store and maintain state
- When a component simply receives props and renders itself to a page, it is a ‘stateless component’ and can be created using a pure function. This component is also known as dumb Components or presentation components
What is the difference between the state and the properties?
- State is a data structure for default values of data required when a component is mounted. States can mutate over time, but most of the time as a result of user event behavior.
- Props(short for properties) is the configuration of the component. Props is passed from the parent component to its children, and is immutable as far as the children are concerned. A component cannot change its props, but it can group the props of its children together (unified management). Props isn’t just data either — callback functions can also be passed through Props.
Make ajax requests during that lifecycle
In the React component, network requests should be made in componentDidMount. This method is executed when the component is first “mounted” (added to the DOM) and only once in the life of the component. More importantly, you can’t guarantee that the Ajax request will be completed before the component is mounted, which means you’ll try to call setState on an unmounted component, which won’t work. Making a web request in componentDidMount ensures that there is a component that can be updated.
What does refs do in React
Refs can be used to get a reference to a DOM node or React component. Good examples of when to use Refs are managing focus/text selection, triggering command animation, or integrating with third-party DOM libraries. You should avoid String Refs and inline ref callbacks. Refs callbacks are recommended by React.
What is a Higher Order Component?
A higher-order component is a function that takes a component as an argument and returns a new component. HOC runs you to reuse code, logic, and bootstrap abstractions. The most common is probably Redux’s Connect function. Instead of simply sharing libraries and simple combinations, HOC’s best approach is to share behavior between React components. If you find yourself writing a lot of code in different places to do the same thing, consider refactoring your code into reusable HOC.
Why is it recommended that the argument passed to setState be a callback rather than an object
Because updates to this.props and this.state can be asynchronous, you cannot rely on their values to calculate the next state.
How to prevent component rendering
Returning NULL in a component’s Render method does not affect the lifecycle method that triggers the component
What is the key when rendering a list? What is the purpose of setting the key
Keys help React identify items that have changed, been added, or been removed. Keys should be assigned to elements in the array to give the element a stable identity. The best way to select a key is to use a string that uniquely identifies a list item. Most of the time you will use IDs in the data as keys. When you don’t have stable IDs for the items being rendered, you can use the item index as the key of the render item, but this is not recommended, as re-render will be slow if items can be reordered
What is the purpose of calling super(props) (in the constructor)
Subclasses cannot use this until super() is called; in ES2015, subclasses must call super() from constructor. The reason for passing props to super() is so that (in subclasses) constructor can access this.props.
JSX
JSX is a syntactic extension of the JavaScript syntax and has all the functionality of JavaScript. JSX produces React “elements.” You can wrap any JavaScript expression in curly braces and embed it in JSX. Once compiled, JSX expressions become regular JavaScript objects, which means you can use JSX inside if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.
Angular
How components communicate with each other in Angular
Props down
- Calls the child component, passing values through custom properties
- The child component internally receives the value of the property through Input
Events up
- Define a method with parameters in the parent component
- When the child component is called, the custom event and the previous method are bound
- Inside the child component, events and values are triggered by Output and EventEmitter.
The eight major components of Angualr are briefly described
Templates are HTML Bindings enhanced by directives, pipes, Components, etc Directives for extended HTML, including event binding, property binding, two-way data binding, etc., are structural and attribute Directives as well as Directives in other modules such as routing modules, Service encapsulates the common parts of components and applications, such as data or methods, into a Service to facilitate DependencyInjectionCopy the code
Lifecycle hook functions that are common in Angular
NgOnChanges: Responds when Angular sets it to receive data binding properties of the current and previous object values.ngOnInitInitialize the component/directive after the first ngOnChange trigger. This is the most common method used to retrieve template data from a back-end service. NgDoCheck: Detects and executes when Angular context changes. Is called each time change detection is run.ngOnDestroy: Eliminates directives/components before Angular destroys them. Unsubscribe observable objects and detach from event handlers to avoid memory leaks. Component-specific hooks: ngAfterContentInit: Component content has been initializedngAfterContentChecked: after Angular checks the external content of the binding projected into its view.ngAfterViewInit: After Angular creates the component's view. NgAfterViewChecked: After Angular checks the binding of the component viewCopy the code
How routing works in Angular
The Angular application has a single instance of the router service, and every time the URL changes, the corresponding route matches the routing configuration array. On a successful match, it applies redirection, at which point the router builds a tree of ActivatedRoute objects, including the current state of the router. Before redirecting, the router checks to allow the new state by running a protection (CanActivate). The Route Guard is simply an interface method that the router runs to check for Route authorization. After the protection runs, it parses the routing data and activates the router state by instantiating the required components to
Explain the use of RJX in Angular
Rxjs is an asynchronous way of processing data provided by Microsoft and is used in Angular to handle network communication. Create an Observable and subsribe.this.http.get(' ').subscribe((data) = >{})Copy the code
Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.
Past wonderful recommendation
Canvas Pit Climbing Road
Don’t know SEO optimization? An article helps you understand how to do SEO optimization
Canvas Pit Road
Wechat small program development guide and optimization practice
Talk about mobile adaptation
Front-end performance optimization for actual combat
Talk about annoying regular expressions
Obtain file BLOB stream address to achieve the download function
Vue virtual DOM confused? This article will get you through the virtual DOM once and for all
Git Git
Easy to understand Git introduction
Git implements automatic push
How do I use Git in my work
Interview Recommendations
Front ten thousand literal classics – the foundation
Front swastika area – advanced section
More exciting details: personal homepage