Although July is not a harvest season, it is a very hot month. I do not know how many partners like me, under the sun rush about in a variety of interview journey. The interview is a long process. But it’s also a process that allows you to improve quickly. It involves a lot of blood and tears. Before going to the interview, we must first have a solid foundation of knowledge and rich enough project experience (in my case, almost three complete project experience, the total time is almost one year). Then is the expression ability, you should be able to put your answer to the interviewer to describe clearly, pay attention to professional vocabulary, which will greatly improve the interviewer’s impression of you!
preface
Learning without thought is useless; thought without learning is perilous. After going through all the major factories, I found that in fact, every company pays more attention to the investigation of basic ability. Only when the basic is well mastered, all the front-end knowledge can be sorted out in a series. So no matter what the interview question is, you can easily answer it. This is a summary of the underlying principles of all the interview questions I’ve been asked, not the questions I’ve been asked. On the one hand, this can help you to go over the basis of JS can also help me to deepen my understanding. Below I will be divided into modules to explain not a knowledge point. The length is too long, please be patient to read!!
First, CSS interview
1. Box model
The box model in CSS includes IE box model and standard W3C box model. The box model still belongs to box-sizing property. The box model corresponds to border-box and Content-box. Border-box :width = left/right + left/right padding+ contentWidth Any padding and border specified by the width = content+padding+border element will be drawn within the specified width and height.
2. Front one pixel problem (draw a 0.5px line)
Transform :scaleY (0.5) : transform:scaleY (0.5) : transform:scaleY (0.5) : Transform :scaleY
- 1. Set the reference position of the target element
- 2. Add a pseudo-element before or after to the target element and set the absolute position
- 3. Add 1px borders to fake elements
- 4, use box-sizing: border-box to enclose the width and height of the border
- 5. Set the width and height to 200%
- 6. The whole box model is reduced to 0.5
- 7. Adjust the position of the box model with the upper left corner as the baseline transform-Origin: 0
Method 2: border-image Sets the border of the image
3. The difference between Transition and animation
Animation and Transition have most of the same properties. They both change the value of an element’s properties over time. The main difference is that Transition needs to trigger an event to change its properties, while Animation does not need to trigger any events to change its properties over time. And transition to 2 frames, from…. To, and animation can do it frame by frame.
4. The indeterminate height DIV is centered
1. Using flex
Set display: flex in the parent box; justify-content: center; align-items: centerCopy the code
2. Use the CSS transform
Parent box :display:relative Div: transform: translate(-50%, -50%); position: absolute; top: 50%; left: 50%;Copy the code
3. Display: table – cell
Parent box Settings :display:table-cell; text-align:center; vertical-align:middle; Div Settings: display:inline-block; vertical-align:middle;Copy the code
5, floatingThe corresponding link
- Features: A floating element affects not only itself, but other elements around it
- Why clear the float? If a block-level element has no height set, its height is supported by its child element. When a float is used on the child element, the child element is removed from the document stream. That is, there is nothing in the parent element to support its height, so the height of the parent element is ignored. This is called a height collapse
- How to clear the float
1. Define the height of the parent element 2. Float the parent element 3. Clearfix: use content generation to clear float. Clearfix :after {// :after selector inserts content after the selected element.""; Display: block; // Block level element display clear:both; // Clear the previous element} without breaking the document flow, with no side effectsCopy the code
6. CSS selector classification
Basic: 1.id selector (id="name") 2. class selector (class="head") 3. Label selector (body, div, ul, li) 4. Global selector (*) Complex: 1. Combined selector (.head. Head_logo) 2. Descendant selector (#head. Nav ul li from parent set to descendant set) 3. Group selector (div, SPAN, img {color:Red} with the same style of tag group display) 4. Inheritance selector 5. Pseudo-class selector (link style, pseudo-class of a element) 6. Child selector (div> P, greater than sign >) 7.CSS adjacent adjacent sibling selector (H1 + P, plus sign +)Copy the code
Priority:
Different levels: summary sort:! Important > Inline Style > ID selector > Class selector > Tags > Wildcards > Inheritance > Browser default properties
- 1. Add! Import overrides element styles defined anywhere on the page
- 2. The style written inside the element as a style attribute
- 3. The id selector
- 4. Class selector
- 5. Label selector
- 6. Wildcard selector (*)
- 7. Browser customization or inheritance
Same level: The last one overwrites the first one
CSS selector parsing rules: Selectors locate DOM elements from right to left to filter out unnecessary style rules and elements early
Inline elements and block elements
A block element | Inline elements |
---|---|
Block elements occupy a row, and by default, their width automatically fills the parent element’s width. Row elements don’t occupy a row, they stay on a row until there is no more space | Row elements have no width and height attributes, and block-level elements monopolize a row even if the width is set |
Block level elements: div P forn ul Li H1-h6 | Span img input a I |
Note: For inline elements, font size specifies the height of their Content Area, since inline box = helf-leading up and down, if leading is 0, in which case, Font size refers to the height of the font, but cannot specify the actual height for each glyph given font height, resulting in a span height greater than line-height
8. How to draw a triangle
Set the width and height and draw the border width: 0; height: 0; border-bottom: 100px solid cyan; border-left: 50px solid transparent; border-right: 50px solid transparent;Copy the code
9. Methods to make elements disappear
Opacity :hidden, display: None, z-index=-1, opacity: 0
- Opacity: 0, which is hidden but does not change the page layout, is also triggered if the element is already bound to events, such as the click event
- 2. Visibility :hidden, the element is hidden, will not change the page layout, but will not trigger events that the element is already bound to
- 3. Display :node: hides the element and changes the layout of the page
10. Why CSS at the top and JS at the back
- 1. After the browser preloads the CSS, it can render the page without waiting for the HTML to finish loading
- 2. HTML rendering does not wait until the page is fully loaded, but rather parses the DOM while rendering.
- 3. Js is written in the tail, mainly because JS mainly acts as the function of event processing. On the one hand, many operations are performed after the page rendering. On the other hand, it can save the loading time, make the page can be more loaded, and improve the user’s good experience
But with the development of JS technology, JS also began to undertake the work of page rendering. For example, our UI can actually be divided, putting render js in front and time processing JS in back
Second, layout interview
1. Flex flex layout
It is easy to center an element (both horizontally and vertically centered) raster system layout, bootstrap grid
2. Column three is the layout
Three columns are layout (two columns on both sides have fixed width, middle column width is adaptive)
- Solution 1: Position (absolute positioning method) Center div needs to be placed at the back of the absolute positioning method principle uses the left and right sides absolute positioning, because the absolute positioning makes them out of the document flow, the center behind will naturally flow to their upper show, and then the margin property, leaving the width of the left and right sides. You can adapt.
- Float :left, float:left, float:left, float:left, float:left, float:left, float:left Right, float takes the left and right elements out of the document flow, and in the middle of the normal document flow, uses margin to specify the left and right margins to position them.
- Scheme three (Holy Grail layout) : the principle is margin negative method. To use the Holy Grail layout, you first need to include a div outside the Center element. The included div needs to set the float property to form a BFC, and the width matches the negative value of the margin
3. Fixed width on the left and adaptive on the right
- Left {float:left}. Right :{width:100%}
- Left {float:left}. Right :{width:cacl(100vw-200px})
- Display: flex Right is set to flex: 1
- Scheme 4: the right div covers a package, and the front, left and package double floating
4, horizontal center
Inline element centered (parent element text-align:center) Block element centered (block element not issued text-align) 1. Margin :auto 2. Width variable: block level change inside line, then text-aligin on parentCopy the code
5, landing the
A BFC is a concept of CSS layout. It is a separate rendering area, an environment in which elements do not affect how external elements generate the BFC: [1] The root element, that is, the HTML element (the largest BFC) [2] float is not none [3] Position is absolute or fixed [4] Overflow is not visible (default). [5] Display: Inline-block, table-cell, Table-caption The internal boxes will be placed vertically, one on top of the other. 2. The margins of two adjacent boxes belonging to the same BFC will overlap. 3. And vice versa, text wrap, set float 4. The area of the BFC does not overlap the float box. 5. Calculate the height of the BFC. The floating element also participates in the calculation of the BFC: 1. The parent div's BFC attribute is triggered so that all child divs are in the same BFC region of the parent div. Margin overlap can be prevented when the BFC belongs to different BFCCopy the code
3, JS interview
1. Front-end event flow
Event flow describes the order in which events are received from the page. It can be divided into: event capture phase In the target phase event bubble phase where the main one is required is the function addeventListener and the last Boolean parameter, if true, means that the event handler is called in the capture phase; If false, the event handler is invoked during the bubbling phase.
- 1. Event capture phase: The actual target div will not accept events during capture phase, that is, during capture phase, events will stop from Document to and again
- 2. In the target phase: Events occur and are processed in div, but event processing is considered part of the bubbling phase.
- Bubbling phase: Events propagate back to the document
Stop bubbling event.stopPropagation()function stopBubble(e) {
if(e &&e.topPropagation) {// If the event object is provided, it is not e.topPropagation ()}else {
window.event.cancelBubble = true//IE prevent bubbling}} preventDefault event.preventdefault ()function stopDefault(e) {
if (e && e.preventDefault) {
e.preventDefault()
} else{// The IE browser blocks the default action of the function window.event.returnValue =false}}Copy the code
How events are captured and then bubbled up:
In the DOM standard event model, capture is followed by bubble. 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 event.
Which events do not support bubbling events:
Mouse event: mouserLeave mouseEnter Focus event: blur Focus UI event: Scroll resizeCopy the code
2. Event delegate (improve performance)
Summary: Event delegate means that listeners are not set on the event (direct DOM), but on its parent element. With event bubbling, the parent element can listen for events on the child element and respond differently by determining the type of the DOM element on which the event occurred.
- For example: the most classic is UI and LI tag event listener, for example, when we add events, we use the event delegate mechanism, not directly on the LI tag, but on the UL parent element
- Benefits: Binding of dynamic elements is appropriate, new child elements also listen for functions, and events can be triggered
3. What does the js new operator do
The new operator creates an empty object whose prototype points to the constructor’s prototype, which is returned after execution. If you don’t want the properties and methods of the parent class, add new to function prototype.
4. The direction of this
- When a function is called as a method of an object, this refers to that object.
- 2. As a normal function, this refers to the window.
- Constructor call, this refers to the object returned.
- The arrow function’s this binding looks at the object under which this is defined. If there is nesting, this is bound to the nearest layer object
4.1 Principle of arrow function this:
This is fixed, not because the arrow function has a mechanism to bind this, but because the arrow function does not have its own this, so the inner this is the outer code block’s this. Because it does not have this, it cannot be used as a constructor.
4.2. How to change the direction of this?
1. Use the arrow function of ES6; 2. Use that = this inside the function; 3. Use apply, call, bind; 4. New instantiates an object
4.3 The difference between bind,apply and call
The first argument to apply and call is the same as the object to be changed. The second argument, apply, is an array, and call is arg1,arg2… In this form. Bind one returns a function that will not be executed immediately and the other takes arguments (the first argument points to this, and the following arguments are passed)
5, depth copyRefer to the link
Basic types of | Reference types |
---|---|
Basic types: undefined, null, Boolean, String, Number, Symbol in memory of fixed size, stored in a stack memory | Reference types: Object, Array, the Date, the Function, the RegExp etc. Value is the Object of reference types Stored in the heap memory, stack memory storage variable identifier and the object is stored in the heap memory address. |
Copy of a primitive type: a new copy is created to assign the value to a new variable. Changing the value does not change the old object | Copy of a reference type: essentially copying a pointer, which eventually points to the same object, changes its value and changes the new object |
Note: Primitive type comparisons == perform type conversions
Shallow copy | Deep copy |
---|---|
Slice () concat() object.assign | Json.parse () serializes a JS object into a JSON string json.stringify () deserializes a JSON string into a JS object es6 expansion {… } |
Memory is re-created on the stack, and the basic types of objects are unaffected before and after the copy. Only one layer of an object is copied, and child objects cannot be copied | A recursive copy is made of the child objects in an object. The copy does not affect each other |
6. SetTimeout and setInterval mechanisms
Because JS is single threaded. When the browser encounters etTimeout and setInterval, it will finish executing the current code block first. Before that, it will push the timer into the browser’s waiting time queue. After the browser finishes executing the current code, it will check whether there is a task in the event queue and then execute the code in the timer
7. Front-end cross-domain problems
Same Origin policy (Protocol + port number + domain name must be the same)
- 1, JSONP cross-domain (can only solve get) principle: dynamically create a script tag. SRC attributes using script tags are not subject to the same origin policy because all SRC and href attributes are not subject to the same origin policy and can request third-party server resource content
Step: 1. Create a script tag. 2. Interface parameter, must have a custom function name, otherwise the background cannot return data 4. Accept the returned data by defining the function nameCopy the code
- 2. Document. domain The basic domain name is the same as the subdomain name
- 3, window.name uses a browser window to load all domain names to share a window.name
- After the access-Control-Allow-Origin HTTP response header is set on the server, the browser will Allow cross-domain requests
- Take advantage of the new H5 feature window.postmessage ()
The iframe element creates an inline frame (inline frame) that contains another document (setTimeout for asynchronous loading) A floating frame or container that is used to set text or graphics. It is the same as the main domain of document.domain, and the web communication with different subdomains is set to the superdomain: document.domain ='demo.com'2. Window. postMessageht(data, URL), H5 API, start cross-domain communicationCopy the code
8. Image preloading and lazy loading
8.1. Preloading:
Images are pre-loaded and rendered directly from the local cache when the user needs to view them
Why use preloading: Load some of the main content of a web page before it loads to provide a better user experience and reduce wait time. Otherwise, if the content of a page is too large, there will be white space.
Solution to blank pages: 1. Preload
2. Use SVG station images to quickly build up some structures and replace the current placeholders when the requested data arrives
The preloading method is as follows:
1. Use HTML tags 2. Use Image objects 3. Use XMLHTTPRequest objects, but finely control the preloading processCopy the code
8.2. Lazyload
Client optimization, reduce the number of requests and delayed requests, improve user experience, reduce the loading of invalid resources, prevent concurrent loading of too many resources will block THE loading of JS, affecting the normal use of the website
Principle: First, set the SRC attribute of the picture on the page to an empty string, while the real path of the picture is set with the data-original attribute. When the page is rolling, we need to listen for the Scroll event. In the callback of the Scroll event, we can determine whether our lazy loaded picture has entered the visible area. Lazy loading can be achieved if the SRC property of the image is set to the value of data-original in the visible area.
9, function throttling and anti – shake
Image stabilization | The throttle |
---|---|
Trigger the same event multiple times over a short period of time, only one last time, or at the beginning of the execution, not in between. Like getting on a bus and waiting for the last passenger to get on | Throttling is a function that continuously triggers events during the execution of a function at a certain time interval. Throttling dilutes the frequency of your execution, such as executing a function once every 1 second, regardless of how many events are triggered within that 1 second |
Scroll mousewhell Mousemover Touchmove onresize, there is corresponding code to implement function throttling and anti-shake.
Js garbage collection mechanism
JS has automatic garbage collection mechanism.JS memory life cycle (the life of a variable) 1. Allocate the space you need var a = 20 2. Alert (a + 10) 3 When not applicable, the garbage collector will free the memory space a = null 3.JS every fixed time to perform a free operation, the general is the algorithm by mark cleaning 4. In local scopes, it is easy for the garbage collector to make a judgment and collect, while in global scopes it is more difficult, so the global variable tag cleanup algorithm should be avoided: The most common method of garbage collection is when a variable enters the execution environment, such as declaring a variable in a function, the garbage collector marks it as' entered ', and when the variable leaves (after the function completes execution), it marks it as' left '. The garbage collector marks all variables stored in memory at run time and then removes variables in the environment and any variables referenced by that variable in the environment (closures). The variables that remain marked after this is done are the ones to be deletedCopy the code
11. Some test methods
Never use Typeof for objects and arrays, because both types return Object.
- TypeOf () is Boolean,Number, symbol, undefined, String. For reference types: return object except function. Null returns object.
- InstallOf () checks if A is an instance of B. InstallOf checks prototypes.
- ToString () is a prototype method for Object. For Object objects, toString() returns [Object Object]. For other objects, you need call/apply to return the correct type information.
- The hasOwnProperty() method returns a Boolean indicating whether the object has the specified property in its own properties, ignoring properties inherited from the stereotype chain.
- The isProperty() method tests whether one object exists on another object’s prototype chain.
- Valueof: All objects have valueof. If any original value exists, it defaults to converting the object to its original value. If the object is a compound value, and most objects do not really represent an original value, the default valueof() method simply returns the object itself, rather than the original value
12. Differences between splice and slice, map and forEach, filter() and reduce(
1. The slice(start,end) method returns the selected element from an existing array, and returns a new array containing the elements from start to end (without the element). Splice (): This method adds or removes items from the array and returns the deleted items. Splice (index, howmany, Item1... Itemx) ·index arguments: must, integers specify where to add or remove, negative numbers specify where to remove from the end of the array ·howmany arguments: must, number of items to remove, ·item1.. Itemx: Optional, adds a new item to the array. 3.map() : returns a brand new array. Used when changing data values. ForEach (): does not return anything of value and does not intend to change the data. It simply wants to do something with the data. It allows callback to change the elements of the original array. The filter() method creates a new array of elements by checking all the elements in the specified array that match the criteria. It uses function to do the processingCopy the code
Js \ CSS block
Js blocked | The CSS block |
---|---|
While downloading JS, all browsers block all other activities, such as downloading other resources, rendering content, etc. Continue to download other resources and render content in parallel until JS has been downloaded, parsed, and executed. In order to improve the user experience, the new generation of browsers support parallel downloading of JS, but JS downloading still blocks downloading of other resources (e.g. Images, CSS files, etc.). | Because browsers maintain the order of CSS and JS in HTML, stylesheets must be loaded and parsed before the embedded JS executes. The embedded JS will block subsequent resource loading, so the CSS above will block the download. |
Class creation and inheritance
(es6) in the class, extends
14.1 Inheritance:
- Function Cat(){} Cat. Prototype = new Animal(); Cat.prototype.name = ‘cat’; Multiple inheritance cannot be implemented
- Constructor inheritance: Use the parent class’s constructor to enhance a subclass instance. function Cat(name){Animal.call(this); this.name = name || ‘Tom’; } cannot inherit properties from the parent prototype chain and check with installOF method
- Instance inheritance: Adds new features to the parent class instance as a return for the subclass instance
- Copy inheritance: copying attributes and methods from a parent element
- Combinatorial inheritance: a combination of structural inheritance and archetypal inheritance
- Parasitic combined inheritance: By parasitic, we add a Super function (without instances and methods) to the constructor inheritance to make it point to the parent’s constructor chain and cut off the instance properties of the parent class, so that when the constructor of the parent class is called twice, the method/properties of the parent class are not initialized twice
Constructor A and constructor B (Object. Prototype)
function A(....) {} A.prototype... function B(....) {} B.prototype... A.prototype = object.create (b.prototype).props (props).props (props).props (props).props (props)) Create = function (o) {var F = function () {}; F.prototype = o; return new F(); };Copy the code
Closures and prototypes
15.1. Understanding closures
- 1. Inner functions have access to the parameters and variables that define their outer functions. (Lookup up the scope chain, storing the values of variables in the outer scope in memory rather than destroying them after the function is called) Design private methods and variables to avoid contamination of global variables
- 2, function nested function
- The essence is to connect the inside and outside of a function. The advantage is that you can read variables inside a function, keeping their values in memory at all times and not clearing them automatically after the function is called
15.2 Defects of closures:
1. The disadvantages of closures are that resident memory increases memory usage and can cause memory leaks when improperly used 2. If closures are not needed for some special task, it is not wise to create functions in other functions if they are not necessary because closures have a negative impact on script performance, including processing speed and memory consumption.Copy the code
15.3 Understanding of memory
Out of memory and memory leaks (not enough to use | use don’t return)
- 1. Memory overflow: Out of memory occurs when the program does not have enough memory space to use. For example, if you request an integer but store it for a long, you are out of memory
- 2. Memory leak: after the program has applied for memory, it cannot release the applied memory space. The harm of a memory leak can be ignored, but the consequence of memory leak accumulation is very serious. Anonymous functions return functions
15.4. Scope
Scope :(consists of the current environment and the upper environment of a series of variable objects!! Ensure that the variables and functions that are accessible in the prior execution environment are in order, and that the scope chain variables can only be accessed upwards.
Definition: consists of a series of variable objects in the current environment and the upper environment (functions nested functions, internal sequential access to variables or objects)
To ensure that the variables and functions in the current execution environment are in order, the variables in the scope chain can only be accessed by the up-access variables to the window object and terminated, the down-access of the scope chain is not allowed. Change scope with try.. All variables directly assigned to a definition are automatically declared as global scope
Scope: A set of rules governing how the engine looks up variables (identifiers are the names of variables or functions) in the current scope and nested subscopes by their identifier names (global and local scopes only) (the scope exists when it is created). Code execution is divided into two phases: 1. Code compilation phase: this phase is defined when the compiler has completed translating the code into executable code. Code execution stage: the js engine completes, mainly executes the big mother, this stage execution context is created (the object is created) execution context: an uncertain object, there are several properties and variables, it is created when the call. This function is called to see the object to which this points, which is the context (created only when called).Copy the code
15.5. Scope chainsRefer to the link
· When code is executed in an environment, a scope chain of variable objects is created, for example: Var name ="Tom" function sayHi() {alert('Hi,'+name)} sayHi() var name ="Tom" function sayHi() {alert('Hi,'+name)} sayHi() When the function is executed to name, the local environment is searched first; otherwise, the scope is searched; in the global environment, the name is found and returned. This orderly process of finding variables is based on scope. · Scope chain is the ordered access of all variables and functions that the execution environment is guaranteed access toCopy the code
15.6. Prototype Chain
Prototype chain: The constructor of a function’s prototype chain object points to the function itself by default. In addition to having prototype properties, for inheritance purposes, the prototype chain pointer _proto_ points to the prototype object at the next level, which still has a similar structure. So you can use _proto_ to always point to the prototype Object, and Object prototype Object with object.prototype. proto=null to indicate the top of the prototype chain. Thus formed the js prototype chain inheritance. At the same time, all JS objects have the basic defense of Object
Server side interview
1. Status code
2XX (The request status has been successfully processed) 200 The server has successfully processed the request and provided the requested web page. 201 The user has created or modified data successfully. 202 A request has been entered in the background. 404 The server could not find the requested page. 404 The server could not find the requested page. 404 The server could not find the requested page. 503 The server is currently unavailable (overloaded or down for maintenance)Copy the code
2, 304 cache principle (added Etag tag. Last-modified)
- 1. The server first generates the Etag, which the server can use later to determine whether the page has been modified. Essentially, the client passing this token back to the server requires server validation (client cache)
- 2.304 is the HTTP status code used by the server to indicate that the file has not been modified and does not return the content. The browser that receives this status code will find the file cached by the browser
- 3. Process: The client requests A page A. The server returns to page A and adds an Tage client to render the page and stores Tage in the cache as well. The client requests page A again and passes the resource requested last time along with the ETage to the server. The server checks Tage. And determines that the page has not been modified since the last client request. Go straight back to 304
Last-modified: A client requests a resource with a last-Modified attribute that marks the time when the file was last modified on the server. The client requests this URL a second time, according to the HTTP protocol. The browser sends an if-modified-since header to the server asking If the file has been Modified Since the event, and returns 304 If it has not
With Last-Modified, why ETag? Last-modified is incorrect if two changes are made to a file in less than a second. Some servers do not know exactly when the file was Last Modified. Some files also make periodic changes. However, its contents do not change (only the Modified event). We do not want the client to think that the file has been Modified and Get ETag again. Why last-Modified? 2. If ETag comparison is generated for each scan, it is obviously much slower than direct comparison of modification time. ETag is the entity value of the requested variable (the Hash value of the file's index section, size, and last modified time) 1. The value of ETag is obtained by the server Hash the file's index section, size, and last modified event.Copy the code
3. Get/POST differences
- 1. Get data is stored after the URL as? Split URL and transfer data, parameters are connected with &; The POST method places the submitted data in the Body of the HTTP package
- 2. The size of data submitted by GET is limited (because browsers limit the length of URLS), while the size of data submitted by POST is not limited
- 3. Get uses Request. queryString to obtain the value of a variable, while POST uses Request. from to obtain the value of a variable
- 4. Data submission through get brings security problems. For example, when you log in to a page and submit data through GET, the user name and password will appear in the URL
4. Summary of HTTP and HTTPS
4.1. Understanding of HTTP protocol
1. Hypertext transfer protocol, which is used for hypertext transfer from the World Wide Web server to local resources 2. Based on TCP/IP communication protocol to transfer data (HTML, image resources) 3. The object-oriented protocol based on application layer is suitable for distributed hypermedia information system due to its simple and fast method. The request line consists of the request line, the header, the blank line, and the request data. It describes the request type, the resource to be accessed, and the HTTP version to be used. The request header is a blank line that specifies the additional information to be used by the server. The blank line following the request header is the required request data, also known as the body, which can be added to any other data. A message header consists of HTTP protocol version number, status code, and status message. It is used to describe some additional information to be used by the client. The blank line after the message header is the necessary Response body. Text information returned by the server to the client.Copy the code
4.2. The difference between HTTP and HTTPS
http | https |
---|---|
Is a secure HTTP channel, simply a secure version of HTTP, encrypted over SSL | Hypertext transfer protocol. Is a client – and server-side request and reply (TCP) standard that makes browsers more efficient and reduces network traffic |
4.3, HTTP1.0, 1.1, 2.0 differences
Differences between 1.0 and 1.1:
Long connections: HTTP1.0 requires the keep-alive parameter to tell the server to establish a long connection, whereas HTP1.1 supports long connections by default
Save broadband: HTTP1.1 supports sending only a header message (without any body information)
Host domain (setting up virtual sites, that is, multiple virtual sites on a Webserver can share the same IP port) : HTTP1.0 does not have a host domain
Differences between 1.1 and 2.0:
- 1. Http2 uses binary text to transfer data, rather than http1 text format, binary in the protocol parsing and extension better
- 2. Data compression: The information header is compressed and transmitted by HPACK, which saves the network traffic brought by the information header
- 3. Multiplexing: One connection can process multiple requests concurrently
- 4. Server push: we support HTTP2.0 webserver request data, the server will incidentally push some client need resources together to the client, so that the client again create a connection to send a request to the server side for. This is a great way to load static resources
5. Web summary
5.1. Web Caching
1. The Web cache is a copy that exists between the client and the server. After you make the first request, the cache stores a copy of the output based on the request. Benefits of caching (1) Reduce unnecessary requests (2) reduce server stress, reduce server consumption (3) Reduce network latency, speed up page opening (directly read browser number)Copy the code
5.2 Common Web security and protection principles
- 1. SQL injection principle: the SQL command is inserted into the Web form to submit or enter the life, so as to deceive the server to execute malicious SQL command defense: 1. Verify user input. 2. Dynamic concatenation SQL is not applicable
- 2.XSS (Cross-site scripting attack) : Inserts malicious HTML tags or JS code into web pages. For example: place a seemingly secure link in the forum, steal the user information in the cookie prevention: 1. Use POST instead of GET to submit the form. 2. Avoid disclosing user’s implicit information in cookies
- 3.CSRF(cross-site request disguise) : requests from trusted users are camouflaged. For example, Teacher Huang Yi’s WebApp music request data is camouflaged by CSRF cross-site request to obtain QQ music data
- The differences between XSS and CSRF are as follows: 1.XSS obtains information without knowing the codes and packets of other users’ pages in advance. 2
5.3 CDN(Content Delivery Network)
1. Avoid Internet bottlenecks and links that may affect data transmission speed and stability as much as possible. Make content transfer faster and more stable. 2. Key technologies: Content storage and distribution 3. Basic principle: Various cache servers are widely used and distributed to the regions or networks where users can access the cache servers. When users access the network, global load technology is used to direct users' access to the nearest cache server, and the cache server directly responds to the user's request (global load technology)Copy the code
6. Front-end rendering process (TCP three-way handshake, DOM tree rendering)
6.1 Complete process from entering URL to obtaining pageRefer to the link
1. Query NDS(domain name resolution) to obtain the IP address corresponding to the domain name. Query the browser cache 2. The browser establishes a TCP connection with the server (three-way handshake) 3. The browser sends an HTTP request to the server (requesting and transmitting data) 4. The server receives the request, generates HTML code based on the path parameters, and returns it to browser 5 after some processing at the back end. The browser takes the complete HTML page code and starts parsing and rendering. If it encounters external CSS or JS, the image is the same as step 6. The browser renders a complete page based on the resources it receivesCopy the code
6.2 TCP three-way handshake
The client sends c request to connect to the server for confirmation, and the server also initiates connection confirmation.
- First handshake: the client sends a connection request. The server can only accept the segment of the packet sent by the client
- Second handshake: The server sends a link to the customer service to confirm that the customer service has received the packet
- Third handshake: The server confirms that the client has received the packet segment
DOM -> CSSOM -> render -> layout -> print
Process: parse HTML and build dom tree -> build render tree -> layout render tree -> render tree concept: 1. Build a DOM tree: The rendering engine parses an HTML document by first converting tags into DOM nodes (including jS-generated tags) in the DOM tree to generate content tree 2. Build a rendering tree: parse the corresponding CSS style file information (including JS-generated styles and external CSS) 3. Layout rendering tree: Recursively calls from the root node to calculate the size, position, etc of each element. 4. Draw the render tree: Walk through the render tree and redraw each node using the UI back-end layer: Once the box's position, size, and other properties, such as color and font size, are determined, the browser paints each color according to its own characteristics and renders the content on the page triggering a redraw condition: changing the element's appearance attributes. Redraw refers to the behavior of the browser triggered by the change of the appearance of an element. The browser will redraw the element according to the new attributes, so that the element will present a new appearance. Note: Table and its internal elements need multiple computations to determine the attribute values of its nodes in the rendering tree, which takes more time than the same elements. Try to avoid table layout rearrangement (reconstruction /reflow /reflow) : Backflow occurs when part (or all) of a rendered book needs to be rebuilt due to changes in element size, layout, hiding, etc. Every page needs a backflow, so rearranging the page the first time it is rendered will definitely affect redrawing, but redrawing won't necessarily affect rearrangingCopy the code
7, front-end storage summary
7.1 Storage mode and transmission mode
- IndexBD: is a local h5 repository that stores some data in the browser. Without the Internet, the browser can read data from it and use it offline. 5m
- 2.Cookie: confirm user identity through browser record information, maximum 4KB, which limits data transmission, request performance will be affected
- 3.Session: a mechanism used by the server side to record the client status (session_id exists set_cookie sent to the client side and saved as cookie)
- 4. LocalStroage: local storage of H5. Data is permanently stored in the customer service terminal
Cookie, sessionStorage,localStorage is stored on the client, and session object data is stored on the server. In fact, only the session ID is transmitted between the browser and the server. The server finds the corresponding user session object based on the session-ID. 2. Cookie data is always carried in the HTTP request of the same origin, which is passed back and forth between the browser and the server, where session-ID sessionStorage is stored.local3, size limit difference, cookie data does not exceed 4KB,localSessionStorage is only valid until the current browser window is closed, it is destroyed immediately after closing (temporary Storage).localStorage is always validCopy the code
7.2 SessionStorage and localStorage differences:
SessionStorage is used to store the data in a session locally. The data can only be accessed in the page using a session (i.e. during the first communication) and the data will be destroyed after the session ends. SessionStorage is not a persistent local storage. Session level storage 2. LocalStorage a localStorage used for persistence that will not expire unless data is deletedCopy the code
7.3 Understanding of Token, Cookie and Session
-
1. Token is a way to verify the user’s identity, such as when you authorize (log in) a program, based on whether you have authorized the software
-
2, cookie is written in a TXT file on the client, which includes login information, so that the next time you log in a website, it will automatically call cookie automatic login username server generation, sent to the browser, browser save, the next request again sent to the server (stored with login information)
-
Session is a solution for preserving state between the client and the server. The session is destroyed (representing the session between the server and the client) and the cookie stores the sessionID, which will be sent by the request. The sesion is generated because of the Request object.
7.3 Token-based authentication: (Simplest Token: UID unique user identification + time current event stamp + sign signature)
Authentication on the server 3. The server returns a signed token to the client 4. The server authenticates the token and returns data. Each request requires the token cookie to be distinguished from the session. Cookie data is stored on the client's browser and session data is stored on the server. 2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. 3. Sessions are stored on the server for a certain period of time. Cookies should be used to reduce server performance when the number of accesses increases. 4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20.Copy the code
7.4 Differences between Session and Token
- Session authentication is only a means of authentication that stores simple User information in the session. The sessionID is unpredictable. It only exists on the server and cannot be shared to other websites or third-party apps
- 2. Token is oAuth token, which provides authentication and authorization. Authentication is for users, and authorization is for App. Tokens are unique and cannot be transferred to other apps or to other users. (For APP)
- 3. The session state exists on the server, and only the session ID exists on the client. The Token state is stored on the client
7.5. What are the disadvantages of cookies? (Advantage: saves client data, sharing the burden of server storage)
1. Limitation of quantity and length. A maximum of 20 cookies can be generated per specific domain name (chorme and Safari have no limit).Copy the code
Five, write in the back
Because of the length, I prepared a TXT document, which has more front-end basics. Including Vue,React, Node, data structure, etc. Learning always requires constant accumulation and summary. The purpose of writing this article is also very clear, if the summary of the bad place welcome to point out and comment below, or you think a good knowledge point, not summed up, also hope to be able to share, to help you, but also improve their own.