1. A complete HTTP service process
When we type in the address bar of a Web browser:
www.baidu.com
What exactly happened?
- DNS domain name resolution, associating a web address with an IP address.
- Send a TCP connection, locate the corresponding server based on the IP address, and establish a connection between the browser and the server.
- Send an HTTP request.
- The server responds to the HTTP request, and the browser gets the HTML code
- The browser parses the HTML code and requests resources in the HTML code (such as JS, CSS, images, etc.).
- The browser renders the page to the user.
- Server Shutdown The TCP connection is disabled.
Understand can:
1. How did DNS find the domain name?
DNS domain name resolution is a recursive query, the process is, first to the DNS cache -> cache can not find the root domain name server -> the root domain name will go to the next level, such a recursive search, found, returned to our Web browser IP.
2. Why is HTTP implemented based on TCP?
TCP is an end-to-end reliable interface connection protocol, he is a relatively low-level protocol; HTTP is based on the transport layer TCP protocol and does not have to worry about the various problems of data transmission (when errors occur, it will be retransmitted)
3. How does the browser render the page as the last step?
A) Parsing HTML files to form a DOM tree b) parsing CSS files to form a rendering tree C) parsing while rendering d) JS is run in single thread. JS may modify the DOM structure, meaning that it is unnecessary to download all subsequent resources before JS execution is completed. Therefore, JS is single thread and will block subsequent resource downloads
2. How do browsers render pages?
- Step 1: After sending a request to the Web server, the source code in the index.html page is returned
- Step 2: The browser assigns a main thread that automatically parses and executes code ‘from top to bottom and left to right’
- Step 3:
-
- When the browser encounters a link request, it starts a new thread to load the resource file (without blocking main thread parsing).
-
- If you encounter a style, parse it normally, and then parse the DOM structure after parsing
-
- If @import is encountered, the main thread is told to fetch the resource. After the import and parsing is complete, dom rendering will continue, which blocks the main thread
- Step 4: If a Script tag style is encountered, the main thread takes the resource from the server and parses it, then proceeds to render the DOM structure. Put js last in case JS manipulates the DOM without a value.
-
- You can give the tag async or defer properties and make them asynchronous, or put them at the bottom without blocking DOM rendering
- Step 5: Generate DOM tree and CSS render tree
- Step 6: Generate an HTML rendering tree, refactoring and redrawing the display page
There are two functions:
DOMContentLoaded
The DOMContentLoaded event is fired after the initial HTML document has been fully loaded and parsed, without waiting for the stylesheet, image, and subframe to complete loading. This event is triggered when the DOM tree is available and the JS execution is loaded.
Load event trigger:
The LOAD event is triggered when the JS, CSS, and images in the DOM structure of the page and asynchronously loaded JS, CSS, and images are loaded. There are two concepts:
Refactoring (reflux) : Changes in the size or position of elements that result in a rearrangement of the layout. The process of recalculating the location and size of elements is called refactoring.
- Trigger refactoring:
- The first time the page is rendered
- Element size position changes
- Adding removes the visible DOM
- Browser size changes
Redraw: element style changes (color, background and other non-layout changes)
Redraw does not necessarily lead to redraw (reflow), but redraw optimizations are certain:
- 1. In real project development, if you don’t have a lot of CSS code (or a mobile project), you can use inline styles to reduce HTTP requests and speed up page rendering.
- Link is placed at the top for faster loading back into the CSS
- Script is placed at the bottom to retrieve DOM elements or to not block DOM rendering
- 2. Reduce backflow:
-
- Abandon traditional DOM manipulation in favor of vUE data-driven view. Notice the style and animation changes at 🆗
-
- Style set changes, multiple styles written in a class, through the class to change the style, you can write the operation style at the end of the DOM tree
-
- Cached values are fetched directly from the cache when they need to be changed, thus separating reads and writes and putting them into the render queue for one render
-
- Element batch modification. If you need to add multiple DOM elements, you can use document fragments or template strings
// Create document fragments, add them to them, and then add them to the dom we want to add
let frag=document.createDocumentFragment();
for(let i=0; i<10,i++){
let span=document.createElement('span')
frag.appendChild(span)
}
navBox.appendChild(frag)
Copy the code
-
- Manipulating the DOM offline: Taking elements out of the document stream and then modifying them only causes redrawing, not backflow.
-
- Apply animations to elements with position property absolute or fixed to avoid affecting the layout of other elements. This is just a redraw, not a backflow.
-
- CSS hardware acceleration: Using transform, opacity, and filters triggers hardware accelerators instead of backflow and refactoring
3. HTTP caching mechanism
- When the browser sends the first HTTP request, it can perform cache negotiation during the response. Data can be retrieved from the cache later in the send request process.
3.1 Browser Cache Classification
The browser cache is divided into strong cache and negotiated cache. The simple process for the browser to load a page is as follows:
- The browser determines whether a strong cache has been hit based on the HTTP header for the resource. If hit, the resource is added directly to the cache and the request is not sent to the server. (Strong cache)
- If the strong cache is not hit, the browser sends a resource load request to the server. The server determines whether the browser’s local cache is invalid. If available, the server does not return the resource information and the browser continues to load the resource from the cache. (Negotiated cache)
- If the negotiated cache is not hit, the server returns the full resource to the browser, which loads the new resource and updates the cache. (New request)
Strong cache
- When a strong cache is hit, the browser does not send the request to the server. In Chrome developer tools, the HTTP return code is 200, but the Size column will display as (from cache).
- Strong caching is controlled using the Expires or cache-Control fields in the HTTP return header to indicate how long a resource is cached.
Expires:
The cache expiration time is a specific time point on the server, such as Expires:Thu,31 Dec 2037 23:59:59 GMT
Cache-Control
Is aRelative time
For example, cache-control :3600 indicates that the validity period of the resource is 3600 seconds. Since the time is relative and compared to the client time, server-client time deviations do not cause problems. Cache-Control:max-age=31536000
Negotiate the cache
What the hell is negotiating? Send a request to the server asking if the contents of my cache have been updated. If not, use the cached resources and return 304. If updated, the new resource is returned with status code 200
If the strong cache is not hit, the browser sends the request to the server. The server determines whether the negotiation cache is matched according to last-modify/if-modify-since or Etag/ if-none-match in the HTTP header. If a hit is made, the HTTP return code is 304 and the browser loads the resource from the cache.
- Etag/ if-none-match returns an entity tag (Etag). ETag ensures that each resource is unique, and changes in resources lead to changes in ETag. If the ETag value changes, the resource status has been modified. The server determines whether the cache is hit based on the if-none-match value sent by the browser.
An ETAG is sent in the first response, an ETAG is requested in the second request, and negotiation caching is performed if the two ETags are equal
Problem solving thinking
- HTTP caching technology is mainly used to improve the efficiency of the server concurrency, some resources can be directly cached, without resending the request.
- When the browser sends the first HTTP request, it can perform cache negotiation during the response. Data can be retrieved from the cache later in the send request process.
- Strong caching is utilized
Cache-Control:max-age=31536000
Field setting; The negotiation cache is set using Etag/ if-none-match.
- The browser determines whether a strong cache has been hit based on the HTTP header for the resource. If hit, the resource is added directly to the cache and the request is not sent to the server. (Strong cache)
- If the strong cache is not hit, the browser sends a resource load request to the server. The server determines whether the browser’s local cache is invalid. If available, the server does not return the resource information and the browser continues to load the resource from the cache. (Negotiated cache)
- If the negotiated cache is not hit, the server returns the full resource to the browser, which loads the new resource and updates the cache. (New request)
4. The fetch and axios
Fetch is also a means of communication between the front and back ends. It is an alternative to the XMLHttpRequest object, which is based on Promises and is provided natively by browsers.
Axios is a Promise-based HTTP library that can be used in browsers and Node.js. It is essentially a encapsulation of XHR.
Advantages and disadvantages of FETCH:
Advantages:
- Native API provided by browser, performance is better.
- Fetch () has a modular design, with apis scattered over multiple objects (Response, Request, Headers), which makes more sense.
- Fetch () processes data through a Stream object and can be read in chunks, which is helpful for improving website performance and reducing memory footprint. It is useful for scenarios requiring large files or slow network speeds.
Disadvantages:
- After the fetch() sends the request, fetch() will only report an error if the network is faulty, or if the connection is not available. In other cases, fetch() will not report an error, but will consider the request successful.
- Fetch does not support timeout control and cannot block the request process
- Fetch has no way of natively listening for the progress of requests, and we want to see the progress bar when uploading large files. XHR can detect progress.
Pros and cons of Axios:
Advantages:
Create XMLHttpRequests from the browser, which can be used for communication on the Web side. You can also create HTTP requests from Node.js for server-side communication.
- There are request interceptors and response interceptors, which can do some data processing and conditional verification in real time.
- You can set a timeout and cancel the request at any time.
- Automatically convert JSON data
- The client supports XSRF defense
- Some concurrent request interfaces are also provided
5. Communication between multiple tabs in the browser (multiple pages)
- Browser data storage is mainly local storage. That is, localStorage methods such as localStorage and Cookie are called to realize data communication of multiple pages under the same source.
5.1 the Local Storage
- A Local Storage is used to store data. However, because the event Storage exists, it can also monitor the Storage status to achieve communication between pages. In Chrome and Edge browsers, the event Storage must be triggered by other same-origin pages.
/ / A page
window.onstorage = function(e) {
console.log(e.newValue); // previous value at e.oldValue
};
/ / B page
localStorage.setItem('key'.'value');
Copy the code
5.2 the WebSocket
WebSocket is a new HTML5 protocol that aims to create an unrestricted two-way communication channel between the browser and the server, for example, so that the server can send a message to the browser at any time. Implement multi-tab instant messaging.
A few key steps
You have to do it on the front and the back, and you have to do it on the front and the back
function socketConnect(url) {
// Step 1: Create a WebSocket instance to connect to the WS protocol
let ws = new WebSocket(url);
// Step 2: write the open method, the connection will be triggered, can send data in it
ws.onopen = e= > {
console.log('Connection successful', e)
ws.send('I'm sending a message to the server'); // The client communicates with the server
}
// Step 3: The message method listens for messages returned from the server
ws.onmessage = e= > {
console.log('Server side returns:', e.data)
// do something
}
// Step 4: You can also negotiate the error and close methods to monitor for faulty links or close
return ws; // Returns the WebSocket object
}
let wsValue = socketConnect('ws: / / 121.40.165.18:8800'); / / the websocket object
Copy the code
This can be done using the encapsulated socket. IO
Install in the local project
//npm i socket.io -S
//1. Import the js file
<script src="/socket.io/socket.io.js"></script>
//2. Invoke the IO interface
const socket = io();
Socket. On ('message',callback); accept
socket.emit('Custom Event name', name);
Emit ('message', name); //4.
socket.on('message'.(msg) = > {
console.log(msg);
});
Copy the code
The second new html5 browser feature, SharedWorker
Ring letter customer service, seven mo customer service to buy
6.XSS, CSRF and how to prevent it
XSS stands for Script Cross Site attack and can be described as a hacker attacking your browser and tampering with the browser’s normal display in order to steal user information.
6.1 It is divided into three categories:
- 1. Reflexes — When a browser sends a request, the XSS code appears in the URL to tamper with the request information and make the server return additional information, such as personal and private information.
- 2. Storage – The user saves some information and sends it to the server. In this process, hackers insert malicious scripts to save users’ information in the database, so that other users can see the comments when they submit them, causing great impact.
- 3. Dom – when the server sends HTML to the browser, hackers add malicious scripts to maliciously alter the style of the site.
6.2 Defense Measures: ‘
(1) Input filtering: filter the content entered by users. Reliable input validation for all user-submitted content, including URL, query keywords, POST data, etc., only accept content submitted within the specified length range, in appropriate format, using the expected characters, and filter the rest. (Both client and server)
(2) Output escape
For example, when inserting untrusted data between HTML tags, the first thing to do is to create an HTML Entity encoding HTML character Entity for the untrusted data
function htmlEncodeByRegExp (str){
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g."&");
s = s.replace(/</g."<");
s = s.replace(/>/g.">");
s = s.replace(/ /g." ");
s = s.replace(/\'/g."& # 39;");
s = s.replace(/\"/g.""");
return s;
}
var tmpStr="<p>123</p>";
var html=htmlEncodeByRegExp (tmpStr)
console.log(html) //< p> 123< /p>
document.querySelector(".content").innerHTML=html; //<p>123</p>
Copy the code
(3) Use HttpOnly cookies
Mark important cookies as HttpOnly, so that when the browser makes a request to the Web server, the cookie field is attached, but the cookie cannot be accessed in the JS script. This avoids XSS attacks that use JavaScript document.cookie to get cookies.
Modern Web development frameworks such as vue.js and React. Js have been designed with XSS attacks in mind to further abstract, filter and escape HTML interpolation. We can avoid XSS attacks in most cases if we use them skillfully and correctly.
CSRF
CSRF refers to cross-site request forgery. The user originally wants to visit website A (phishing website), but during this process, the link to visit website B (such as bank) is displayed. After the user clicks, the hacker impersonates the user to visit website B and get the user information of website B. CSRF defense measures are mainly taken by the server. The server verifies the refer field in the request header and adds token or mobile verification code.
7.vuex
VueX is a mechanism to implement global state (data) management of components and facilitate data sharing among components. It acts as a common repository for data shared by all components.
7.1 Three Features
- Centrally manage shared data in VUEX for easy development and maintenance.
- It can efficiently realize data sharing among components and improve development efficiency.
- The data stored in Vuex is responsive, keeping it in sync with the page in real time.
7.2 Procedure
- 1. Install
- 2. Import and use it
- 3. Create a Store object and export it
- 4. Mount the Store object to the Vue instance
7.3 options
7.3.1 State is the only data source
State provides a unique common data source, and all shared data should be placed in the state attribute of the Store for storing simultaneous updates of mutations data. Actions operate data asynchronously, but submit it to mutations for simultaneous updates
How does the component get data?
// The component gets data
this.$store.state.xxx
/* Component changes data: 1. The current component binding method uses the dispatch method to trigger the actions function (dispatch) 2. Decompose commit from actions to trigger function 3 on mutations. In the function on mutations, deconstruct state and modify the data */
// If asynchronous operations are not required, skip actions and the component triggers the function on mutations directly via commit ()
Copy the code
7.3.2 modules module
- The Store object also has a Modules option for modularizing data management. Smaller store repositories can be built into it
- If you need to manipulate data in the module:
- $this.$store.state.home.name = this.$store.state.home
- You need to add a module prefix to the method name, for example, home/
modules:{
home: {namespaced:true.// Enable the namespaceStates: {name:'CAI Xukun'
},
mutations:{ },
actions:{}
},
category: {},cart: {},profile:{}
}
Copy the code
7.4 Mapping Methods
Vuex also provides several methods to map global data and methods to your own
1. Use mapState to map the calculated attributes of the current component
import { mapState } from "vuex";
// Use it in the computed option of the component. mapState(["count"]),
...mapState('home'["count"]),
Copy the code
2. Map the methods in mutations to the methods of the current component through mapMutations
import {mapMutations} from 'vuex'; methods: { ... mapMutations(['sub']),
// Map the global sub method to the current component method, and then use it as its own method
}
Copy the code
3. Map the methods in actions to the methods of the current component using mapActions
// Step 1: Introduce functions into the component
import { mapActions } from "vuex";
// Step 2: Map the specified action function to a function of the current component, and the current component can use it as its own function
export default {
methods: {
...mapActions(["subAsync"]),}};Copy the code
8. Encapsulate components
9. Cross domain
- Cross-domain refers to data communication between different domains (protocol, domain name, and port number) with browser participation.
- Cross-domain occurs because the browser’s same-origin policy prevents cross-domain requests for security reasons.
- There are three ways to solve the cross-domain problem: â‘ CORS cross-domain resource sharing â‘¡ JSONP â‘¢ server proxy
-
- Cross-domain resource sharing is preferred with CORS, then with JSONP if the browser does not support CORS, and finally with proxies
Solution 1: CORS cross-domain resource sharing (IE10 for the backend)
Allow cross-domain access-Control-allow-origin: *// indicates that all domain names are allowed to request it across domains
Access-Control-Allow-Origin: http://127.0.0.1:5500 // Only cross-domain requests for specified domain names are allowedThe browser sends the request, the back end adds the Access-Control-Allow-Origin header to the response header, the browser receives the response, and the browser does nothing if the request is in the same domain. ⑤ If it is a cross-domain request, the browser will check the response header to see if cross-domain access is allowed. ⑥ If cross-domain access is allowed, the communication is complete. ⑦ If the desired cross-domain domain name is not found or not contained, the response result is discardedCopy the code
Scheme 2: Jsonp
- The principle of JSONP: Script tags across domains are not blocked by browsers. JSONP mainly uses script tags to load cross-domain files.
- The disadvantage is that only support for get methods is limited and insecure and may be subject to XSS attacks.
Cross-domain implementation using JSONP:
- The front end declares a callback function whose name (such as show) is passed as a parameter value to the server that requests data across domains, and whose parameter is to fetch the target data (the data returned by the server).
- To create a
<script>
Tag, assign the cross-domain API data interface address to script SRC, and pass the function name to the server at that address. The callback = show).- When the server receives the request, it passes the parameters as a function call.
1.The backend creates an interface. Note that the following AAAA is arbitrarily defined by the front end:`https://www.imooc.com/api/http/jsonp?callback=aaaa`
2.This interface opens data like this, transferring data in the form of a function call: aaaa({"code": 200."data": [{"word": "jsp" },
{ "word": "js" },
{ "word": "json" },
{ "word": "Introduction to js" },
{ "word": "jstl"}}]);3.The front end simply introduces the interface in the script tag and then declares an AAAA function based on the callback= aAAA we define in the interface4.This function is called when the request is sent, passing the data through the function callCopy the code
Server side ready JSONP interface:https://www.imooc.com/api/http/jsonp?callback=handleResponse
/* The front end loads the JSONP interface manually or dynamically */
const script = document.createElement('script');
script.src ='https://www.imooc.com/api/http/jsonp?callback=handleResponse';
document.body.appendChild(script);
// Declare the function
const handleResponse = data= > {
console.log(data);// Get the data
};
// It is equivalent to passing arguments to the function through the execution of the function
Copy the code
Scheme 3: server proxy
Using the feature that communication between servers does not need cross-domain, we can solve the cross-domain problem in the development environment by setting the server proxy in the vUE.config.js configuration file when using the VUE framework.
// The proxy function of devServer in vue.config.js is configured
module.exports = {
devServer: {
proxy: {
// If your address starts with/API, it will request the address in target
'/api': {
target: '<url>'.ws: true.changeOrigin: true.// Whether to enable the proxy
// This option makes the/API null
pathRewrite : {
'^/api' : ' '
}
}
}
}
}
Copy the code
10. General roadmap for front-end authentication
- 1 Some AXIos requests require tokens. We configure tokens in the AXIos request interceptor
- 2 Some pages need to be logged in to view we can also use routing navigation guard router.beforeEach to determine token
- 3. The sidebar of the background system. Different positions have different permissions, and the sidebar they see and the modules they can operate are different.
- People with different permissions log in and show him different sidebars.
- Sidebars are generally routing-related pages, which need to be generated in a loop. The routing array is different for different people, so the loop generated sidebar will be different. See below for details:
This allows you to control the sidebar display