css
The box model
- Standard box model: element width = margin-left + border-left + padding-left + width + padding-right + border-right + margin-right
- Width = margin-left + width + margin-right height = content height + padding + border;
box-sizing: content-box // Box-sizing: border-box // box-sizing: padding-box //Copy the code
Something in the middle
height: 200px; width:200px; margin:0 auto; display: flex; justify-content: center; Align-items: centerw, position: Absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); Position: absolute; top: 50%; left: 50%; Margin-left: width/2 of the box; Margin-top: height/2 of the box; display:table; margin:0 auto; Etc.Copy the code
Implement a box whose height is half its width
Set the parent element's font-size, eg: self width: 10em; Height: 5em width: 100px; height: 0; padding-top: 50%;Copy the code
way1 emThe way of.fu {
font-size: 20px;
}
.son {
height: 5em;
width: 10em;
border: 1pxsolid red; } way2How to compute using the new CSS features:root {
--my-width: 200px;
--my-height: calc(var(--my-width) / 2);
}
div {
background: yellow;
width: var(--my-width);
height: var(--my-height); Three} waypadding-topThe way of.fu {
width: 100px;
}
.son {
padding-top: 50%;
background: red;
}
Copy the code
What properties does an animation have and what are their values
CSS animation-name: animation name (default: none) animation-duration: duration (default: 0) animation-timing-function: Time function (default value: ease) animation-delay: delay time (default value: 0) animation-iteration-count: number of cycles (default value: 1) animation-direction: Animation direction (default value: normal) animation-play-state: state of playback (default value: running) animation-fill-mode: fill mode (default value: None)Copy the code
What attributes do you use for animation
- Transform performs better because of the Transform property, which enables the browser’s GPU acceleration, which reduces the drawing time of smooth animations and does not trigger redrawing
Draw a triangle
- Use the border
- Using pseudo class
- Use the clip – path
- The use of canvas
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
.fu {
width: 0;
height: 0;
border-top: 50px solid black;
border-right: 50px solid red;
border-bottom: 50px solid green;
border-left: 50px solid blue;
}
.fu1 {
width: 0;
height: 0;
border-top: 50px solid black;
border-right: 50px solid transparent;
border-bottom: 50px solid transparent;
border-left: 50px solid transparent;
}
/ * 2, by means of pseudo class The lower right triangle * /
.pseudo-ele {
width: 20px;
height: 20px;
background: transparent;
/* There must be more than direct kill */
overflow: hidden;
}
.pseudo-ele:after {
display: block;
width: 150%;
height: 150%;
content: ' ';
background: red;
transform: rotateZ(45deg) translateX(10px);
}
.demo {
clip-path: polygon(0 100%.50% 0.100% 100%);
}
</style>
</head>
<body>
<div class="fu">
</div>
<br>
<div class="fu1">
</div>
.
<! --html-->
<div class='pseudo-ele'></div>
<! -- -->
<div class="demo" style="width: 300px; height: 300px; margin: auto; background: red;">
</div>
</body>
</html>
Copy the code
js
How browsers render
-
The first sets the background to red, the second to yellow, and the third to blue. Does the page blink?
-
Currently, the third color is displayed, and there is no flash operation
-
The first sets the background to red, the second sets the background to yellow and executes the for loop 100,000 times, and the third sets the background to blue
-
The current final display is also the third color, there will be no flash operation
-
Graphical User Interface (GUI) is a Graphical User Interface used for computer operations.
Reason :GUI rendering threads and JS engine threads are mutually exclusive because JavaScript is DOM manipulable. If you render the interface while modifying these element attributes (i.e., JavaScript thread and UI thread are running at the same time), you may get inconsistent element data before and after the rendering thread. The GUI thread is suspended while the JavaScript engine is executing, and GUI updates are kept in a queue until the engine thread is idle. The GUI rendering thread and JS execution thread are mutually exclusive. When the browser executes the JS program, the GUI rendering thread will be stored in a queue until the JS program is executed. Therefore, if the JS execution time is too long, this will cause the page rendering to be inconsistent, resulting in the page rendering load blocking feeling.
The difference between for of and for in
-
Objects can only iterate over arrays and nested objects
-
For of prints the value and for in prints the subscript and key
-
For in iterates over properties on a custom prototype. For of does not
var arr = ['nick'.'freddy'.'mike'.'james']; arr.name = "Array"; for (var key in arr) { console.log(key + ':' + arr[key]); } // 0: nick // 1: freddy // 2: mike // 3: james / / name: array console.log('----------- splitter -----------'); for (var item of arr) { console.log(item); } // nick // freddy // mike // james Copy the code
The way to get the maximum value in an array
var max = Math.max.apply(null, arr);
Copy the code
The type of js
- Simple types: NULL, number, string, symbol, Bigint, Boolean, undefind
- Complex type: Object
closure
- (closure = “function” and “sum of accessible variables in function body”)
- Function: Hides variables
Prototype chain
- The reason is that every object has a __proto__ attribute, which points to the prototype of that object’s constructor.
- An object can be linked by __proto** to the prototype object of the upstream constructor, which also has a **proto__, thus forming a prototype chain.
- function Function()._proto__ == Function.prototype
- Function.prototype.constructor== function Function()
- Function.prototype.__proto** == Object. Prototype the Function’s __proto** also points to the Object prototype
This points to the problem
- Whoever calls this points to it. Arrow functions don’t have this
Learn about service workers
MDN description: Service Workers essentially act as proxy servers between Web applications, browsers, and the network (when available). This API is designed to create an effective offline experience that intercepts network requests and takes appropriate action to update resources from the server based on whether the network is available. It also provides a portal to push notifications and access background synchronization apis.
Summary description: A middleman role between the server and the browser. If a service worker is registered in the website, it can intercept all the requests of the current website and make judgment (corresponding judgment program needs to be written). If it needs to send requests to the server, it can transfer them to the server. If you can use the cache directly, you just return it to the cache and don’t transfer it to the server. Thus greatly enhancing the browsing experience.
Some API for strings
- split()
- indexOf()
- lastIndexOf()
- match()
- Replace (), parameter 1 is old, parameter 2 is new
- startwith()
- endwith()
- slice()
- substring()
- substr()
- includes()
- trim()
- trimLeft()
- trimRight()
- padStart()
- padEnd()
- charAt()
- CharCodeAt () gets the Unicode encoding for a character
- Str.touppercase ()/str.tolowerCase () uppercase/lowercase case, etc
Some API for arrays
- splice()
- indexOf()
- lastIndexOf()
- includes()
- slice()
- map()
- forEach()
- reduce()
- reduceRight()
- pop()
- push()
- shift()
- unshift()
- filter()
- some()
- every()
- reverse()
- concat()
- Find (),findIndex() returns the first value/index that satisfies the element
- Sort () and so on
regular
Object
- Parse (json.stringfy (obj)), recursive
- The merge of object.assign (). The first layer is a deep copy and the second layer is a shallow copy
- Object. The prototype. The toString () is used to check the type of a variable, precise and more accurate than typeOf
- Addresses are stored on the stack and referenced objects are stored in the heap
Macro task, micro task
-
Macro task.
- Script (can be understood as the outer synchronization code)
- setTimeout/setInterval
- The UI rendering/UI events
- PostMessage, MessageChannel
- SetImmediate, I/O (Node.js)
-
The task.
- Promise
- mutationObserve,
- nextick
- await
Performance optimization
- DNS pre-resolution, caching (strong and negotiated caching)
Event loop
White screen time,The first screen timeTo calculate
-
Bad time
- When the Performance API is available
Hang time = firstPaint - performance. Timing. NavigationStart;Copy the code
- When the Performance API is unavailable
White screen time = firstpaint-pagestartTime;Copy the code
<head> <meta charset="UTF-8"> <title>hang</title> <script type="text/javascript"> // Browsers that are incompatible with Performance. Timing, such as IE8 window.pageStartTime = Date.now(); </script> <! Page CSS resources --> <link rel="stylesheet" href="common.css"> <link rel="stylesheet" href="page.css"> <script type="text/javascript"> // Blank screen time end point window.firstPaint = Date.now(); </script> </head> Copy the code
-
The first screen time
- Or is the loading pictures of the slowest time – performance. Timing. NavigationStart;
OSI network layer 7 model
-
What is the
- OSI (Open System Interconnect) model, which is called Open Communication System Interconnection Reference model, is a standard framework proposed by the International Organization for Standardization (ISO) that tries to make all kinds of computers Interconnect in the world as a network
-
OSI divides a computer network architecture into seven layers
- The application layer
- The presentation layer
- The session layer
- The transport layer
- The network layer
- Data link layer
- The physical layer
http/ https
- HTTPS is a secure version of HTTP. HTTP data is transmitted in plain text, so it is not secure for the transmission of sensitive information. HTTPS is born to solve HTTP insecurity.
Http1.0, HTTP1.1, http2.0
-
http1.0
- By default, you need to re-establish a TCP connection each time you interact with the server
- If you want to establish a long Connection, you need to set a non-standard Connection field
Connection: keep-alive
-
http1.0
- Long connections are supported by default
Connection: keep-alive
That is, more than one TCP connection can be transmittedHTTP
Request and response, reducing the cost and latency of establishing and closing connections- In the load
html
Multiple requests and responses from a file can be transferred over a single connection
- In the load
- Also allows the client request results back don’t have to wait for the last time, can send out the next request, but the server must be in order to receive the order of the client request of echo response as a result, to ensure that the client can distinguish between each request response content, so also significantly reduce the time required to download the entire process
- Added cache policy (strong cache/negotiated cache)
- Added other request methods put, DELETE, options, trace, and connect
- Long connections are supported by default
-
HTTP2.0
-
multiplexing
HTTP/2
reuseTCP
Connections, in which both the client and the browser can simultaneously send multiple requests or responses without having to correspond in sequence, thus avoiding queue congestion.
-
Binary framing
Frames are the smallest unit of information in HTTP2 communication
HTTP/2 transmits data in binary format rather than HTTP 1.x’s text format, which is more efficiently parsed
Split the request and response data into smaller frames, and they are binary encoded
In HTTP2, all communication under a domain name is done over a single connection that can carry any number of two-way data streams
Each data stream is sent as a message, which in turn consists of one or more frames. Multiple frames can be sent out of order, and can be reassembled according to the stream identifier at the head of the frame, which is also the realization condition of multiplexing simultaneously sending data
-
The first compression
HTTP/2 uses “header tables” on both the client and server sides to track and store previously sent key-value pairs, rather than sending the same data through each request and response
The header table exists throughout the lifetime of the HTTP/2 connection and is progressively updated by both the client and the server
- The first request sends all header fields, and the second request only sends differential data, which reduces redundant data and overhead
-
Server push
HTTP2 introduces server push, which allows servers to push resources to clients
The server will incidentally push some resources required by the client to the client, such as in response to a page request, you can bring other pages of resources
Prevents the client from creating a connection and sending a request to the server
This is a great way to load static resources
-
Cache (strong cache/negotiated cache)
Strong caching (response headersExpires 与 Cache-Control )
- Expires
- Expires: Expires is a header introduced in HTTP1.0 that represents a resource expiration time. It describes an absolute time that is returned by the server,
- Expires is limited to local time, and changing the local time can invalidate the cache
Expires: Wed, 11 May 2018 07:20:00 GMT
-
Cache-Contro
- Cache-control, introduced in HTTP / 1.1, takes precedence over Expires and represents relative time
Cache-Control: max-age=315360000
-
The current mainstream approach is to use cache-control to Control the Cache. In addition to max-age to Control the expiration time, there are a few other things to mention
- Cache-control: public can be cached by all users, including terminals and intermediate proxy servers such as CDN
- Cache-control: private can only be cached by the terminal browser, not by the trunk Cache server
- Cache-control: no-cache, the Cache is cached locally first, but after hitting the Cache, the server must verify the freshness of the Cache before using it
- Cache-control: no-store, no Cache is generated
If a cache is hit within the cache validity period, the browser directly reads the local cache resources and negotiates with the server when the cache expires.
Negotiate the cache
The browser negotiates with the server on the second request if the server returns a response header with no cache-control or Expires on the first request, or if the cache-control or Expires attribute is set to no-cache.
If the cache is the same as the server’s latest version of the resource, the server does Not need to download the resource again. The server simply returns the 304 Not Modified status code. If the server finds that the browser’s cache is an older version, the server returns the full contents of the latest resource to the browser. The status code is 200 Ok.
There are two ways for the server to determine if the cache is expired
-
Last-Modified/If-Modified-Since
- Last-modified :Thu, 19 Feb 2019 08:20:55 GMT The server sends last-modified :Thu, 19 Feb 2019 08:20:55 GMT to the client when it requests a resource for the first time. If-modified-since :Thu, 19 Feb 2019 08:20:55 GMT The client sends the request header to the server, which then compares it with the corresponding resource on the server. If the resource on the server is updated, the server returns the latest resource. In this case, the status code is 200. If the server resource is consistent with the radical time requested by the client, the client resource is the latest. If the status code is 304, the client can directly use the cache.
-
ETag/If-None-Match
-
The ETag process is similar to last-Modified, but the difference is that ETag hashes the resource content to generate an information summary. As long as the resource content changes, the summary will change greatly. Through this summary information comparison, it can determine whether the client’s cache resource is the latest. This is more accurate than last-Modified.
! [image-20210801234216312](/Users/lizhidan/Library/Application Support/typora-user-images/image-20210801234216312.png)
301 302 304 307
- 301 permanent redirect
- 302/307 Temporary redirect
- 304 The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned.
- If the web page has not changed Since the requester last requested it, you should configure the server to return this response (called the if-Modified-since HTTP header). The server can tell Googlebot that the page hasn’t changed since it last crawled, saving bandwidth and overhead.
What is the DNS protocol? What is the complete DNS query process?
-
Definition: The Domain Names System (DNS) is an Internet service that translates Domain Names to corresponding IP addresses
- In a nutshell,
DNS
Equivalent to a translator, responsible for the domain name translation intoip
address- IP address: A long number that uniquely identifies a computer on a network
- Domain name: the name of a computer or computer group on the Internet, which consists of a series of dotted names. It is used to identify the computer during data transmission
- In a nutshell,
-
Domain name is a hierarchical structure, from top to bottom for the root domain name, top-level domain name, secondary domain name, tertiary domain name…
- For example,
www.xxx.com
.www
Is the level 3 domain name,xxx
Is the secondary domain name,com
For the top-level domain name, the system has made compatible for the user, the root domain name at the end of the domain name.
Generally, no input is required
- For example,
-
Domain name cache
- Browser cache: After obtaining the actual IP address of the website domain name, the browser caches it to reduce the loss of network requests
- Operating system cache: The operating system cache is actually configured by the user
hosts
file
-
The query process
-
First, search the browser’s DNS cache, which maintains a mapping table of domain names and IP addresses
-
If no match is found, search the DNS cache of the operating system
-
If no match is found, the OPERATING system sends the domain name to the local DNS server. The local DNS server recursively searches its DNS cache. If the search succeeds, the local DNS server returns a result
-
If the DNS cache of the local DNS server is not matched, the local DNS server iteratively queries the DNS cache of the upper-layer DNS server
-
First, the local DNS server sends a request to the root DNS server. The root DNS server returns the TOP-LEVEL DNS server address to the local server
-
After the local DNS server gets the address of the top-level DNS server, it sends a request to it to obtain the address of the permission DNS server
-
The local DNS server sends requests to the DOMAIN name server based on its IP address and obtains the IP address corresponding to the domain name
-
-
The local DNS server returns the obtained IP address to the operating system and caches the IP address itself
-
The operating system returns the IP address to the browser and caches the IP address itself
-
At this point, the browser gets the IP address corresponding to the domain name and caches it away
-
What happens when you enter the URL in the address bar and you hit enter?
-
URL parsing
- Make sure you enter a valid one first
URL
It is also a keyword to be searched, and the operation is based on what you type
- Make sure you enter a valid one first
-
The DNS query
-
TCP connection (three-way handshake)
- The client sends a SYN packet to the server
- The server returns an ACK+SYN packet
- After receiving an ACK+SYN packet, the client sends an ACK packet to the server
-
The HTTP request
- The request line
- Request header
- Request body
-
Respond to the request
-
The status line
-
Response headers
-
In response to the body
After the server responds, the TCP connection is broken by four waves after the page is closed, since HTTP now starts the keep-alive connection by default
-
-
Page rendering
-
When the browser receives a resource from the server, it first parses the resource:
- View the information in the response header and follow various instructions, such as redirection, storing cookies, extracting Gzip, caching resources, and so on
- View the content-Type value of the response header, which is parsed differently depending on the resource Type
The rendering process for the page is as follows:
- Parse the HTML and build the DOM tree
- Parses the CSS and generates the CSS rule tree
- Combine DOM tree and CSS rules to generate render tree
- Render tree (Layout/reflow), responsible for each element size, location calculation
- Render the Render tree (paint), which draws the page pixel information
- The browser sends each layer’s information to the GPU, which then composes the layers and displays them on the screen
-
Three handshakes/four waves Why not two handshakes, or multiple handshakes. Why can’t it be three waves? Multiple waves.
Summary is not less, also can not ## more, more words, waste bandwidth resources, less words, the sender can not determine whether the receiver received the message
Three-way handshake
-
Definition: To establish a TCP connection, the client and the server need to send a total of three packets
-
Role: In order to confirm whether the receiving and sending capabilities of both parties are normal, specify their initial serial number for the subsequent reliability of the preparation of transmission
- First handshake: The client sends a SYN packet to the server, and the initial sequence ISN(C) is specified. In this case, the client is in the SYN_SENT state
- Second handshake: After receiving a SYN packet from the client, the server responds with its OWN SYN packet. To acknowledge the SYN from the client, the ISN+1 of the client is used as the ACK value. In this case, the server is in the SYN_RCVD state
- Third handshake: After receiving a SYN packet, the client sends an ACK packet with the ISN+1 of the server. The client is in the ESTABLISHED state. After receiving the ACK packet, the server is also in the ESTABLISHED state. In this case, a connection is ESTABLISHED
- Final conclusion (By three handshakes, it is established that the receiving and sending capabilities of both parties are normal. Then you can communicate normally.)
- First handshake: The client sends a network packet and the server receives it. Then the server can conclude that the sending capability of the client and receiving capability of the server are normal.
- Second handshake: The server sends a packet and the client receives the packet. Then the client can conclude that the receiving and sending capabilities of the server and the client are normal. However, the server cannot confirm whether the client’s reception capability is normal
- Third handshake: The client sends the packet and the server receives it. In this way, the server can conclude that the receiving and sending capabilities of the client are normal, and the sending and receiving capabilities of the server are also normal
Four times to wave
-
Definition: TCP terminates a connection after four waves
- First wave: The client sends a FIN packet with a specified sequence number. At this point, the client is in FIN_WAIT1(wait) state and stops sending data, waiting for confirmation from the server
- Second wave: After receiving the FIN, the server sends an ACK packet and uses the serial number of the client +1 as the SEQUENCE number of the ACK packet, indicating that the packet is received. In this case, the server is in CLOSE_WAIT state
- Third wave: If the server also wants to disconnect, the server sends a FIN packet with a specified sequence number as the first wave from the client. The server is in
LAST_ACK (Final confirmation)
The state of the - Fourth wave: After receiving the FIN, the client also sends an ACK packet and uses the serial number of the server +1 as the sequence number of its OWN ACK packet. In this case, the client is in TIME_WAIT state. It takes a period of time to ensure that the server receives its ACK packet before it enters the CLOSED state. After receiving the ACK packet, the server is in the CLOSED state
-
The reason for the four waves
- The server disconnects from the receiving client
Fin
After a packet is sent, the connection is not closed immediatelyACK
The packet tells the client that it has received a request to close the connection and only sends it when all the packets from the server have been sentFIN
The packet is disconnected and therefore requires four waves
- The server disconnects from the receiving client
! [image-20210801235307945](/Users/lizhidan/Library/Application Support/typora-user-images/image-20210801235307945.png)
How HTTPS works, how it interacts. How to encrypt it
-
It’s a complicated process, and we need to understand two concepts
-
Symmetric encryption: that is, both sides of communication use the same secret key for encryption and decryption. For example, the secret code of the spy joint is symmetric encryption
Symmetric encryption although very simple performance is good, but cannot solve the problem of sending the secret key to each other for the first time, it is easy to be intercepted by hackers secret key.
-
Asymmetric encryption:
-
Private key + Public key = Key pair
-
Data encrypted with the private key can be decrypted only by the corresponding public key, and data encrypted with the public key can be decrypted only by the corresponding private key
-
Each communication party has its own key pair, and sends its public key to the other party before communication
-
The other party then uses the public key to encrypt the data and responds to the other party. When it arrives at the other party, the other party uses its private key to decrypt the data
-
Asymmetric encryption is more secure, but the problem is that it is slow and affects performance.
Solution:
Then, the two encryption methods are combined. The symmetric encryption key is encrypted with the asymmetric encryption public key, and then sent. The receiver uses the private key to decrypt the symmetric encryption key.
This brings up another problem, the middleman problem:
If there is a middleman between the client and server, the middleman only needs to replace the public key of the communication between the two sides with his own public key, so that the middleman can easily decrypt all the data sent by the two sides.
Therefore, a secure third-party issued certificate (CA) is required to prove the identity of the identity and prevent man-in-the-middle attack.
A certificate includes the issuer, certificate purpose, user public key, user private key, HASH algorithm, and certificate expiration time
But here comes the question, ** If the middleman tampered with the certificate, would the proof of identity be invalid? ** This proof is bought for nothing, this time needs a new technology, digital signature.
- A digital signature is a digital signature that uses the HASH algorithm of the CA to HASH out a digest of the certificate, encrypts the certificate with the CA private key, and finally forms a digital signature.
When someone sends his certificate, I use the same Hash algorithm to generate the message digest again, and then decrypt the digital signature with the CA’s public key to get the CA
Create a message digest and compare the two to see if the middle has been tampered with.
At this time can maximize the security of communication.
-
Why do we have it?HTTPWhy evenHTTPS?
- HTTPS is the secure version of HTTP. HTTP data is transmitted in plain text. Therefore, it is not secure to transmit sensitive information
Retransmission mechanism?
- When a catch is in the promise, it will be called again according to the data code returned in the background
- Or use an interceptor in AXIos to intercept the response and retransmit it according to code
What is cross-domain
-
Dom same-origin policy: Disallows operations on different Dom. In this case, iframes of different domain names are restricted from accessing each other.
-
XmlHttpRequest Same-origin policy: Disables the use of XHR objects to make HTTP requests to server addresses of different sources. Any difference in protocol, domain name, or port is regarded as different domains, and requests between domains are cross-domain operations
Note: any difference between protocol, domain name and port is considered as different domains
How to solve cross-domain
- The json using
- disadvantages
- Only GET requests are supported (because
- Security problems and vulnerable to XSS attacks
- The server side needs to cooperate with JSONP for a certain degree of transformation
How to solve cookie cross domain?
- Settings window. Domian
- The server returns path
XSS CSXF definition
XSS (Cross Site Scripting) Cross-site Scripting attacks
-
XSS, a cross-site scripting attack, allows an attacker to insert malicious code into a page that is intended for use by other users
-
XSS involves three parties: the attacker, the client, and the Web application
-
The goal of XSS is to steal cookies stored on the client or other sensitive information that websites use to identify the client. Once the information of legitimate users is obtained, the attacker can even impersonate legitimate users and interact with the website
“>
-
define
- Storage type
- reflective
- The DOM model
XSS prevention
-
From the previous introduction, you can see that there are two elements of an XSS attack:
- The attacker submits malicious code
- The browser executes malicious code
Cross-site Request Forgery (CSRF) Cross-site request forgery
-
The characteristics of
-
Attacks are generally launched on third party sites, not the site being attacked. The attacked site cannot prevent the attack from happening
-
Attack using the victim’s login credentials in the attacked website, posing as the victim to submit operations; Instead of stealing data directly
-
During the whole process, the attacker cannot obtain the login credentials of the victim, but only “fake” them.
-
Cross-site requests can be made in a variety of ways: image urls, hyperlinks, CORS, Form submissions, and more. Part of the request can be directly embedded in third-party forums, articles, difficult to track
-
-
CSRF prevention
- CSRF is usually launched from third-party websites. Attacked websites cannot prevent attacks, but can only enhance their own protection against CSRF to improve security
Common solutions to prevent CSRF are as follows:
-
Block access to unknown outfields
-
- Homologous detection
- Samesite Cookie
-
Submit by asking for additional information that is available only to the local domain
-
- CSRF Token
- Double Cookie authentication
Prevents web pages from being nested by iframe
<meta http-equiv="X-Frame-Options" content="SAMEORIGIN">
Copy the code
Or more specifically:
<meta http-equiv="X-Frame-Options" content="SAMEORIGIN / DENY ">
Copy the code
Specify specific website:<meta http-equiv="X-Frame-Options" content="ALLOW-FROM http://xxx.xxx.com">
Copy the code
-
X-frame-options has three values:
-
DENY: indicates that the page is not allowed to be displayed in the frame, even if the page is nested in the same domain name.
-
SAMEORIGIN: indicates that the page can be displayed in the frame of the same domain name page.
-
Allow-from URI indicates that the page can be displayed in the frame of the specified source.
-
cmd amd umd commonjs
- CommonJS, where each JS file stores the contents of its module independently (like a bracketed closure). From this scope, we export objects as modules through the module.exports statement and import them through the require statement
function myModule() {
this.hello = function() {
return 'hello! '; }}module.exports = myModule;
Copy the code
- AMD advocates dependency preloading, declaring dependent modules when defining modules
require([module], callback);
Copy the code
- CMD specification is generated in the promotion process of SeaJS in China to advocate nearby dependency (loading on demand), and require when a module is used
define(function (require.exports.module) {
var one = require('./one')
one.do()
// Load on demand
var two = require('./two')
two.do()
})
Copy the code
- UMD is a combination of AMD and CommonJS, which is a cross-platform solution. UMD determines whether any Node.js supported module (exports) exists and uses Node.js module mode if it does. Check whether AMD is supported (define exists). If AMD exists, load modules in AMD mode
(function (window, factory) {
if (typeof exports= = ='object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
window.eventUtil = factory();
}
})(this.function () {
//module ...
});
Copy the code
Es6 array
Promise
Vue source router vuex implementation diff algorithm VUe3 compared to vue2 changes here to observe whether you are a concern about the technology
axios
How do I implement axios interrupts
-
Demand analysis
There are often scenarios in a project where multiple requests are sent consecutively, and asynchrony can result in undesirable results and can have a significant impact on performance.
Scenario: Send a request for each character you enter, but if you type it too quickly, it is not necessary to send the previous request. In this case, you need to cancel the previous request before sending a new one.
-
Axios provides a CancelToken function, which is a constructor that cancels the interface request.
let CancelToken = axios.CancelToken let self = this axios.get('http://jsonplaceholder.typicode.com/comments', { cancelToken: new CancelToken(function executor(c) { self.cancel = c console.log(c) // The c argument is the CancelToken constructor's own CancelToken function }) }).then(res= > { this.items = res.data }).catch(err= > { console.log(err) }) Copy the code
Vue
Implementation principle of vue-Router
How does VUEX work?
this.$nextTick
What do you understand about Keep-alive? How do I cache the current component? How to update the cache? And the principle of
What happens when the Vue instance is mounted?
- The _init method is called when new Vue is called
- Define methods set, set, set, get, delete, delete, delete, watch, etc
- Define events such as on, ON, on, off, emit, emit, emit, off, etc
- Define the _update, forceUpdate, forceUpdate, forceUpdate, destroy life cycles
- Call $mount to mount the page
- Mount it primarily through the mountComponent method
- Define the updateComponent update function
- Execute Render to generate the virtual DOM
- The virtual DOM is generated by _update to the real DOM structure and rendered to the page
Why is the Proxy API used instead of defineProperty API in Vue3.0?
What are the main aspects of Vue3.0 performance improvement?
- Diff algorithm optimization
- Static ascension
- Event listener cache
- SSR optimization
- Source code size (remove some uncommon apis, tree-shanking such as REF, Reavtived, computed, etc., pack only when used, unused modules are eliminated, and the overall size of the package becomes smaller)
- Responsive System (Proxy)
- Vue2 uses defineProperty to hijack the entire object, and then performs a deep loop through all attributes, adding getters and setters to each attribute to achieve responsiveness
- Vue3 overrides the reactive system with a proxy, which does not require deep traversal because it can listen on the entire object
- You can listen for dynamic attributes to be added
- You can listen on the array index and the array length property
- You can listen for delete properties
What are the design goals of Vue3.0? What optimizations have been made?
What is the difference between the Composition Api used by Vue3.0 and the Options Api used by VUe2.x?
webpack
How does Webpack’s hot update work? How does it work?
What are the common loaders?
- File-loader: Outputs files to a folder, referencing the output file with a relative URL in the code
- Url-loader: similar to file-loader, but can inject the contents of files into code base64 if the files are too small
- Source-map-loader: Loads additional source map files to facilitate breakpoint debugging
- Image-loader: loads and compresses image files
- Babel-loader: Convert ES6 to ES5
- Css-loader: loads the CSS and supports features such as modularization, compression, and file import
- Style-loader: Inserts CSS code into JavaScript and loads CSS via DOM manipulation.
- Eslint-loader: Checks JavaScript code through ESLint
What are the common plugins?
- Define-plugin: Defines some environment variables
- Html-webpack-plugin: Simplifies HTML file creation
- Uglifyjs -webpack-plugin: Use UGlifyJS to compress ES6 code
- Webpack-parallel-ugli-fi -plugin: multi-core compression to improve compression speed
- Webpack-bundle-analyzer: Visualizes the volume of webpack output files
- Mini-css-extract-plugin: Extract CSS to a separate file and support on-demand loading
What is the webPack build process?
The running flow of Webpack is a sequential process, from start to finish:
- Initialization parameters: read and merge parameters from configuration files and Shell statements to get the final parameters;
- Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the object’s run method to start compiling.
- Determine entry: find all entry files according to the entry in the configuration;
- Module compilation: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have gone through this step;
- Complete module compilation: After using Loader to translate all modules in step 4, obtain the final content of each module after translation and the dependencies between them;
- Output resources: assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
- Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the file content to the file system. In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening to the event of interest, and the plug-in can call the API provided by Webpack to change the running result of Webpack.
In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening to the event of interest, and the plug-in can call the API provided by Webpack to change the running result of Webpack.
How to optimize front-end performance with WebPack?
Optimizing front-end performance with WebPack means optimizing the output of WebPack so that the packaged end result runs quickly and efficiently in the browser.
- Compress code: Remove unnecessary code, comments, simplify code writing, etc. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize to compress CSS
- Leverage CDN acceleration: During the build process, modify the referenced static resource path to the corresponding path on the CDN. The resource path can be modified using the Webpack to the Output parameter and the publicPath parameter of each loader
- Tree Shaking: Remove pieces of code that never walk. This can be done by appending the parameter optimize-minimize when starting the Webpack
- Code Splitting: Splitting Code into chunks by routing dimensions or components so that it can be loaded on demand and common third-party libraries can be extracted using browser caches: SplitChunksPlugin plug-in for common module extraction, using the browser cache to cache the common code for long periods of time without frequent changes
How to improve the packaging speed of Webpack?
- Happypack: use the process to compile loader in parallel, use the cache to make the rebuild faster. Unfortunately, the author indicates that we will not continue to develop this project. A similar alternative is ththread -loader
- Externals: Take third-party libraries that don’t need to be updated out of webpack and into bundles, reducing packaging time
- DLL: Use Webpack DllPlugin and DllReferencePlugin to introduce DLL, so that some basic will not change the code first packaged into static resources, avoid repeated compilation waste of time
- Cache: webpack.cache, babel-loader.cacheDirectory, and happypack. cache can all use cache to improve rebuild efficiency
- Narrow the search for files: for example, if your files only exist in SRC, include: Path.resolve (__dirname, ‘SRC ‘), of course, in most cases the improvement is limited unless you accidentally build node_modules
How can I speed up webPack building?
- In multi-entry cases, the CommonsChunkPlugin is used to extract common code
- Use the externals configuration to extract common libraries
- The precompiled resource module uses the DllPlugin to precompile NPM packages that we reference but never modify, and then loads the precompiled modules in via the DllReferencePlugin.
- Use Happypack to achieve multi-threaded accelerated compilation
- Use Webpack-Uglify-Parallel to increase the compression speed of uglifyPlugin. In principle, Webpack-Ugli-fi – Parallel uses multi-core parallel compression to improve compression speed
- Use tree-shaking and Scope compensation to weed out redundant code
What are bundle, chunk, and module
- Bundle: Files packaged by Webpack
- Chunk: a chunk is a code block. A chunk is composed of multiple modules for merging and splitting codes
- Module: is a single module under development. In the WebPack world, everything is a module, one module corresponds to one file, and WebPack will recursively find all dependent modules starting from the configured entry
What is the difference between Loader and Plugin?
Different functions
- Loader is a Loader. Webpack treats all files as modules, but Webpack natively only parses JS files, and if you want to package other files, you use loader. So what Loader does is give WebPack the ability to load and parse non-javascript files.
- A Plugin is a Plugin. Plugin can extend the functionality of WebPack to make it more flexible. A number of events are broadcast during the life cycle of a Webpack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by Webpack.
Different usages:
- Loader is configured in module.rules, which means that it exists as a parsing rule for modules. The type is array, each item is an Object, which describes the type of file (test), what to use (loader), and the parameters (options) to use.
- Plugins are configured separately in plugins. Each item is an instance of plugin, and the parameters are passed in through the constructor.
Take a look at the Webpack source code, can you see how the plugin written works
In field
Realize the promise. All
const promiselist = [p1, p2, p3]
Promise.all = function(promiseList) {
return new Promise((resolve, reject) = {
const newList= []
promiseList.forEach(p = {
p.then(res = {
newList.push(res)
if (newList.length == promiseList.length) {
resolve(newList)
}
}, (err) = {
// You can also add the false promise to the array and return me})})})}// The allset of the promise is the same as above, except that the errs from the catch are added to the array and then returned
Copy the code
Implement an array of deduplication
// Array mode
var arr4 = [
{ name: 'a'.id: 1 },
{ name: 'a'.id: 2 },
{ name: 'b'.id: 3 },
{ name: 'c'.id: 4 },
{ name: 'c'.id: 6 },
{ name: 'b'.id: 6 },
{ name: 'd'.id: 7 }];
// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
// (function(mandatory initial value or return value at the end of calculation, mandatory current element, optional index, optional original array), optional function initial value)
var obj = {};
function deWeightFour() {
arr4 = arr4.reduce(function (a, b) {
obj[b.name] ? ' ' : obj[b.name] = true && a.push(b);
return a;
}, [])
return arr4;
}
var newArr4 = deWeightFour();
console.log('%c%s'.'color:red; '.Method 1: ES5,newArr4, newArr4);
// Map
var arr3 = [{ name: 'a'.id: 1 }, { name: 'a'.id: 2 }, { name: 'b'.id: 3 }, { name: 'c'.id: 4 },
{ name: 'c'.id: 6 }, { name: 'b'.id: 6 }, { name: 'd'.id: 7 }];
let deWeightThree = () = > {
let name = 'name';
let map = new Map(a);for (let item of arr3) {
if (!map.has(item.name)) {
map.set(item.name, item);
}
}
return [...map.values()];
}
let newArr3 = deWeightThree();
console.log('%c%s'.'color:red; '.Method 2: ES6,newArr3, newArr3);
Copy the code
Implement a loader/plugin
simulationnew
The new operator does these things:
- It creates a brand new object
- It will be linked by implementation [[Prototype]] (A.K.A. proto)
- It makes this point to the newly created object
- Each object created by new will eventually be linked to the function’s Prototype object by [[Prototype]]
- If the function does not return the Object type Object(including Functoin, Array, Date, RegExg, Error), the function call in the new expression will return the Object reference
function objectFactory() {
const obj = new Object(a);// Create an object
const Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype; // Put the original function's prototype to the new function
const ret = Constructor.apply(obj, arguments); // Change the direction of this
return typeof ret === "object" ? ret : obj; // Return a new object
}
Copy the code
implementationinstanceOf
/ / simulation instanceof
function instance_of(L, R) { //L represents the left expression, R represents the right expression
var O = R.prototype; // take the display prototype of R
L = L.__proto__; // take the implicit prototype of L
while (true) {
if (L === null) return false;
if (O === L) // Return true if O is strictly L
return true; L = L.__proto__; }}Copy the code
Currie,
- Convert a function that takes multiple arguments to a function that takes a single argument
// Non-functional Curryification
var add = function (x,y) {
return x+y;
}
add(3.4) / / 7
// The function is currified
var add2 = function (x) {
//** returns the function **
return function (y) {
return x+y;
}
}
add2(3) (4) / / 7
Copy the code
Write an Ajax request
const request = new XMLHttpRequest() / / create
request.onreadystatechange = function(e){ // Receive and principal logic
if(request.readyState === 4) {// The entire request process is complete
if(request.status >= 200 && request.status <= 300) {console.log(request.responseText) // The result returned by the server
}else if(request.status >=400) {console.log(Error message: + request.status)
}
}
}
request.open('POST'.'http://xxxx') // Establish a connection
request.send() / / send
Copy the code
Implement a deep copy
function deepClone(obj, hash = new WeakMap(a)) {
if (obj === null) return obj; // If it is null or undefined, I will not copy it
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// May be objects or ordinary values if functions do not need deep copies
if (typeofobj ! = ="object") return obj;
// Make a deep copy of an object
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
// Find the constructor from the parent class stereotype, which points to the current class itself
hash.set(obj, cloneObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
// Implement a recursive copycloneObj[key] = deepClone(obj[key], hash); }}return cloneObj;
}
Copy the code
Implement an anti-shake throttling
-
* * if * *
- Definition: The event is executed after n seconds. If it is triggered repeatedly within n seconds, the timer is reset
-
If we press and hold a spring with our finger, it will not spring immediately until you let go
-
Usage Scenarios:
- Button repeat click
- Input box continuous input
- Check whether the scroll slides to the bottom
/ / image stabilization
debounce(func, wait) {
let timeout;
return function () {
let context = this; // Save this point
let args = arguments; // Get the event object
clearTimeout(timeout);
timeout = setTimeout(function () {
func.apply(context, args);
}, wait);
};
},
Copy the code
-
The throttle
-
Basic concept: The same operation is triggered multiple times and executed only once within a specified time range
-
DOM drag
-
Canvas brushes
-
Window resize
/ / throttling throttled(fn, time) { let _arguments = arguments; let canRun = true; return function () { if(! canRun)return; canRun = false; setTimeout(() = > { fn.call(this, _arguments); canRun = true; }, time); }; }, Copy the code
-
Implement Call Apply Bind
/ / implementation call
Function.prototype.call = function(obj, ... reg) {
if(! obj) {this = null
}
obj.fn = this
constresult = obj.fn(... reg)delete obj.fn
return result
}
/ / the apply
Function.prototype.apply = function(obj, ... reg) {
if(! obj) {this = null
}
obj.fn = this
const result = obj.fn([...reg])
delete obj.fn
return result
}
// Bind with call or apply above
Function.prototype.bind = function(obj, ... reg) {
if(! obj) {this = null
}
obj.fn = this
return function(. parmas) {
constresult = obj.fn.call(... [...reg, ...parmas])delete obj.fn
return result
}
}
Copy the code
Implement publish subscribe
class Subscribe {
// Note that the assignment statement is an attribute on the instance
eventHandlerMap = {}
on(eventName, callback) {
if (this.eventHandlerMap[eventName]) {
this.eventHandlerMap[eventName].push(callback)
} else {
this.eventHandlerMap[eventName] = [callback]
}
}
off(eventName, callback) {
if (this.eventHandlerMap[eventName]) {
this.eventHandlerMap[eventName] = this.eventHandlerMap[eventName].filter(f = f ! == callback) }else {
return false}}emit(eventName, params) {
if (this.eventHandlerMap[eventName]) {
this.eventHandlerMap[eventName].forEach(f = {
f && f(params)
})
} else {
return false}}}Copy the code
Es5 inheritance,(handwriting) direct writing (prototype + parasitic) inheritance
- Prototype inheritance (equivalent to shallow copy)
- Parasitic (a function that encapsulates the inheritance process, which internally enhances the object in some form and returns the object)
- Combinatorial inheritance (parasitic combinatorial inheritance, where attributes are inherited by borrowing constructors, common methods are added to stereotypes, and inheritance is parasitic.)
// Prototype inheritance
function object(o) {
var G = function () {};
G.prototype = o;
return new G();
}
var obj = {
name: 'ghostwu'.age: 22.show: function () {
return this.name + ', ' + this.age; }};var obj2 = object(obj);
console.log(obj2.name, obj.age, obj.show());
// Parasitic inheritance
function object(o) {
var G = function () {};
G.prototype = o;
return new G();
}
function CreateObj(srcObj) {
var dstObj = object(srcObj);
dstObj.sayName = function () {
return this.userName;
};
return dstObj;
}
var obj = {
userName: 'ghostwu'};var obj2 = CreateObj(obj);
console.log(obj2.sayName()); //ghostwu
// Parasitic combination
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype.sayHi = function () {
console.log('Hey, Agnehas.');
};
function Student(name, age, sex, score) {
// Borrow constructor: duplicate property value problem
Person.call(this, name, age, sex);
this.score = score;
}
// Change the stereotype to point to ---- inheritance
Student.prototype = new Person(); / / no value
Student.prototype.eat = function () {
console.log('吃东西');
};
var stu = new Student('black'.20.'male'.'100');
console.log(stu.name, stu.age, stu.sex, stu.score);
stu.sayHi();
stu.eat();
var stu2 = new Student('Little Black Black'.200.'the man'.'1010');
console.log(stu2.name, stu2.age, stu2.sex, stu2.score);
stu2.sayHi();
stu2.eat();
Copy the code
Implement a json.parse
var json = '{"name":"cxk", "age":25}';
var obj = eval("(" + json + ")");The eval() function evaluates a string and executes the JavaScript code inside it.
console.log(obj)
Copy the code