Before the end the
A HTML.
1. Reflow and redraw
Backflow: Backflow occurs when part of the render changes in width and height, etc., causing the layout to be rebuilt.
Redraw: Redraw an element when its width and height remain unchanged and only the background color is changed.
Solution: Don’t style the DOM line by line. Instead, define the CSS class in advance and change the DOM className.
Create a layer and use fixed or Absoult position for the animated HTML elements, then modify their CSS without reflow.
Never use a table layout. Because a small change can cause the entire table to be rearranged
2. Several common status codes
1xx: indicates that the request has been received
2xx: success – Request accepted and response header is returned. 200: Request successful, response header is returned.
201 Created request succeeded and a new resource was Created. 202 Accepted server Accepted the request but has not yet processed it
3xx: Redirect – Further action must be taken to complete the request. 301: The requested resource has been permanently moved to the new location. 302: Temporary redirect
303: See Other temporary redirects and always requests new URIs using GET. 304: The contents of the cache have not changed.
4XX: client error – The request has a syntax error or the request cannot be implemented. 400: The request is invalid, and the field name or field type of the data submitted by the front-end is inconsistent with the entity class in the background. 401: Request to authenticate.
403 Forbidden Forbidden access
404: Page not found.
5xx: Server side error – The server failed to fulfill a valid request. 500: The server encountered an unknown condition and cannot handle it. 503: Server overload or maintenance.
3. 1PX problem on mobile terminal
First of all, understand: physical pixels: when mobile devices leave the factory, different devices come with different pixels, also known as hardware pixels; Logical pixels: pixels recorded in the CSS. Window. devicePixelRatio represents the ratio of physical pixels to CSS logical pixels. IPhone devicePixelRatio==2, so you set the 1px border to actually display the physical pixel 2px display, which will be thicker in iPhone.
Solutions:
- Write it as a decimal, but it doesn’t work on ios or Android
- Use Taobao flexible. Js to match. The core seems to be using devicePixelRatio, the ratio of physical pixels to CSS logical pixels. If it’s 2, I’ll set the scale in viewport to 0.5 so that its physical pixels are equal to the 1px pixels CSS wrote.
4. What happens from entering the URL to displaying the page
1. Enter the URL. The HTTP port number is 80, and the HTTPS port number is 443. Check whether the browser has cache, including mandatory cache and relative cache. 3. DNS query, which combines iterative query and recursive query. The browser sends an HTTP request to the server. 6. The browser receives a Response. 7. Page rendering, involving browser rendering process and backflow, redraw
5. Browser rendering process
- Parsing the HTML generates a DOM tree
- Parsing the CSS generates the CSS rule tree
- Combine DOM tree and CSS rule tree to generate render tree
- Traverse the render tree to start the layout, calculate the location information of each node, and draw each node in the render tree to the screen.
6. Web performance optimization
Code level: CSS parses from right to left, setting selector properly. Cache utilization: use CDN acceleration, HTTP cache number of requests: combine CSS styles and JS scripts, use CSS image sprites, image lazy load request bandwidth: Compress files, enable GZIP
- Reduce HTTP requests. Image Base64 encoding, can only be used in large and small pictures.
- Lazy loading of images
- Zip image resource file, // Sprite can be used
- CDN acceleration: Servers distributed in different locations that store static resources so that users can access the nearest node resources.
7.CSRF and XSS
XSS
Cross Site Scripting, full name for Cross Site Scripting, is an attack called cross-site Scripting, where hackers embed malicious Scripting code into pages to steal user information.
Common attack scenarios:
1, user access security site B, then users found that B C XSS holes, sent an E-mail to A user C right now, there are contain malicious script URL (the URL or web address B, I just have A malicious script path), when the user clicks on A visit, because B cookie contains the user’s sensitive information, In this case, user C can use the script to obtain user A’s cookie information and perform some malicious operations.
This attack is called reflexive XSS
2, assume that B is a blog site, a malicious user C in the presence of XSS holes website published an article B, there’s some malicious script in the article, such as img tags, script tags, etc., this blog will inevitably deposited in the database, when other users to access the article a malicious script is executed, then for malicious operation.
This attack, called persistent XSS, stores the data carrying the script into the database and then returns it in the background.
Preventive measures:
1. Filter the input and output results and escape them if necessary
2. Try to use POST and limit the path length when using GET
3. Use HttpOnly to prevent hackers from obtaining user cookie data through scripts, but this does not completely prevent XSS attacks, because HTTP requests do not need to actively obtain cookies
CSRF
Cross-site request Forgery, as the name implies, is a hacker disguised as a user identity to perform some malicious and illegal operations that the user does not want
Common attack scenarios:
Users often visit blog site B, C found website B CSRF vulnerabilities, tried various ways to seduce the user A visit to the C written D dangerous website, and there is no failure, the user A cookie information this time in the dangerous site D have asked request of site B illegal operation, so that users in unwittingly be manipulated.
Img, iframe, and script SRC are not restricted by the same origin policy. Therefore, hackers can use the method of dynamically adding these tags to achieve cross-site requests. Preventive measures:
1. Verification code
2. TokenId token
3. Determine whether the Referer of the request is correct
The differences between CSRF and XSS are as follows: 1. CSRF requires login, but XSS does not
2, CSRF is to request the page API to achieve illegal operations, XSS is to implant JS scripts to the current page to modify the page content.
8. Throttle and prevent shaking
The throttle
When a div is clicked continuously, it is used to limit the function to executing once in a period of time. If the method is fired during the time delay, it will exit the method directly.
Image stabilization
When used to search for input, function stabilization waits some time before executing the target method. If the previous scheduled task is not completed, clear the scheduled task and retry the scheduled task.
2. The CSS
1.CSS parent-child margin collapse
Cause: The outer div will collapse if there is a margin-top in the child div.
Solution: 1. Give the parent box border
2. Put the padding-top on the parent box
3. Give the parent box overflow:hidden
2. The CSS priority
- Add! To property! Important will override any style
- The style written inside the element as the style attribute
- The id selector
- Class selectors
- Label selector
- Wildcard selector
3. The CSS is horizontally and vertically centered
Text-align: center; 2.
Margin: 0 auto;
Vertically centered:
1. Single-line content is vertically centered: line-height: height;
2. Absolute positioning
position: absolute;
top: 50%;
transform: translate(0, -50%);
Copy the code
3. The flex layout
display: flex;
align-items:center; (Horizontal center)justify-content: center;
Copy the code
4. Taobao front-end adaptation scheme
Fit physical pixels.
DPR is the ratio of physical pixels to logical pixels of the device and tells the browser how many actual pixels of the screen should be used to draw a single CSS pixel. When DPR is 2, set the viewPort scale to 0.5 so that a true 1px logical pixel stands for 1px physical pixel. It dynamically sets the font size of the HTML corresponding to the design draft. Take taobao for example, they use 750 design draft, so the HTML font size is 75px, so 1rem is 75px, and when the screen width changes, the HTML font size also changes. (Screen width /750px)*75
5.What is landing
Block formatting Context (BFC). Layout rules are as follows: 1. The inner boxes will be placed vertically, one on top of the other; 2. The vertical distance of boxes is determined by margin. The upper and lower margins of two adjacent boxes belonging to the same BFC will overlap; 3. The left side of each element touches the left side of the containing box, even if there is a float; 4. The BFC area does not overlap with float; 5. The BFC is a separate container on the page, and the child elements in the container do not affect the outside elements, and vice versa; 6. When calculating the height of the BFC, the floating element also participates in the calculation.
Functions of BFC: 1. Avoid margin overlap by using BFC; 2. Adapt two-column layout; 3
3. Js
1. Js data type
- Basic data types: Boolean, Undefined, Null, Number, String, symbol (new in ES6)
- Reference data types: Array, Boolean, Date, Error, Function, Math, Object,
Base data types are stored in stack memory and reference data types are stored in heap memory
2.NaN
NaN is not a number and is not equal to any number. Typeof NaN == number. //true is determined by isNaN()
3. Null and undefined
(1) NULL is an object representing “nothing”, which is converted to a value of 0. Undefined is a primitive value representing “nothing”, which is converted to a value of NaN. When the declared variable has not been initialized, the default value of the variable is undefined
(2) Null is used to indicate that an object does not yet exist. It is often used to indicate that a function attempts to return an object that does not exist. Undefined means “missing value”, that is, there should be a value here, but it is not defined yet
4. Several methods of js to obtain variable types
1. Typeof: Basic types can be determined, but specific object types cannot be determined. And objects created by basic wrapper types such as New String() and array are judged as objects. Typeof principle: js stores the type information of a variable in the lowest 1-3 bits of the variable’s machine code. 2. Instanceof: Variable instanceof Object type, return Boolean, and return true for new Array() instanceof Array or Object. An error is reported when instanceof undefined and null. 3. The Object. The prototype. ToString. Call () : can determine the specific Object type, can put the new Array (), new Reg judgment into an Array and the regular expression () respectively
5. Js cancel event bubbling
W3c standard: Event.stopPropagation (); Ie: event. CancelBubble = true;
Cancel default: e.preventDefault(); Ie: window.event. ReturnValue = false;
Return false even if the default behavior is not bubbling
6. Js closures
Closures are functions that have access to the variables of another function.
For further clarification: When a function executes, an execution-time context is created.
The function also gets the scope chain of its scope, which is the collection of all variable objects accessible to the function. That is, everything accessible to the function is searched up the scope chain until it reaches the global scope.
Each time the function is executed, the corresponding execution environment is unique. When the function is executed, the function will lose the reference to the scope chain, and the JS garbage collection mechanism will be recycled.
However, when the closure exists, that is, when the inner function retains a reference to the external variable, the scope chain is not destroyed, and the inner function can still access the variables of the external function, which is the closure.
Advantages: 1: Prevents variables from being destroyed after the function is executed, and keeps them in memory. 2: Encapsulating functions through closures and immediate execution of functions, global variables may cause naming conflicts, use closures do not worry about this problem, because it is privatized, enhanced encapsulation, thus protecting the security of variables.
Disadvantages: Because it resides in memory, it will increase the memory usage, and it is easy to leak memory when used improperly.
Closure applications:
1. Call setTimeout in the form of function reference
The first argument to setTimeout is usually a function to be executed and the second argument is a delay time.
If a piece of code wants to be called with setTimeout, it needs to pass a reference to a function object as its first argument, but the reference to the function object does not provide arguments for the object to be deferred. At this point, another function can be called to return a call to an internal function, passing a reference to that internal function object to the setTimeout function. The parameters required by the internal function are passed to the setTimeout function when the external function is called. SetTimeout does not need to pass parameters when the internal function is executed. This is because the internal function can still be spoofed from arguments provided when the external function is called.
2. Replace global variables with small scope
// Closures, test2 is a local variable, which is the purpose of closures
// We often use global variables on a small scale, so we can use closures instead.
(function(){
var test2=222;
function outer(){
alert(test2);
}
function test(){
alert("Test closure :"+test2);
}
outer();/ / 222
test();// Test closure :222
}
)();
alert(test2);// undefined, so test2 cannot be accessed here
Copy the code
7. Cross domain
- Jsonp: Dynamically create script tags that are not bound by the same origin policy to get data across domains (only get requests);
- Cors Cross-domain: A normal front-end request carries the Origin field and the URL. After receiving the request, the server sets the access-Control-Allow-Origin field in the response header according to its own cross-domain rules
- Html5’s postMessage method is cross-domain: it cannot exchange data with a server, only between two Windows (iframes). Page A has A reference to page B. A uses the postMessage method to send messages, and B listens for and receives messages via message events:
Depending on your application scenario: simple cross-domain request JSONP, complex CORS, JS cross-domain postMessage between Windows, cross-domain interface in the development environment with Nginx reverse proxy or Node middleware is more convenient.
8. What exactly does the new() operation do
- Create a new empty object.
- Assign the constructor’s scope to the new object (so this refers to the new object);
- Execute the code in the constructor (add attributes to the new object);
- Returns a new object.
9. Js inheritance
(1) Stereotype chain inheritance: the stereotype object that takes the instance of the parent class as a subclass disadvantages: All the prototypes of the instances of the subclass share the attributes and methods of the same instance of the parent class.
(2) Constructor inheritance: Running parent constructors in functions disadvantages: parent functions are not shared and waste memory. Unable to inherit properties and methods on the stereotype chain
(3) Combinatorial inheritance: the combination of prototype inheritance and constructor inheritance. Disadvantages: the parent constructor is called twice, and there are two instances of the subclass, wasting memory. The subclass actually has two properties of the superclass, but the properties of the subclass override the properties of the prototype object
(4) The original type inheritance: pass in the parameter OBj, generate an object inheritance OBJ object shortcomings: not class inheritance, but the original type foundation, the lack of the concept of class
(5) parasitic inheritance (similar to the original type inheritance) : the original type inheritance shell, increase the parameters you want to pass in. Cons: Still no concept of classes
(5) Parasitic combinative inheritance: execute the parent function in the child constructor and create the object. create complex value to OBj. Modify OBJ’s constructor’s finger to point to the child constructor. Finally, OBj acts as the child constructor’s prototype Object.
10. This point
In normal functions, this always refers to the object on which it is called, or, if used as a constructor, to the instance of the object being created. In arrow functions, there is no this of its own, so this in arrow functions is fixed and refers to the object on which the function was defined.
11. Js strict mode
Use “use strict”.
- You cannot use undeclared variables
- Deleting variables and functions is not allowed
- Octal is not allowed
Functions: 1, eliminate code insecurity 2, improve compilation efficiency
12. Let const var distinction
Let: 1, can not declare a variable 2 repeatedly, declare it has block-level scope 3, let declaration is not ahead
4. In short, the variable is not available until it is declared in the code block using the let command. This is grammatically called a “temporary dead zone.”
Const: 1, must have a default value that cannot be changed after being declared
13.promise
1. Promise principle: The promise uses the observer pattern. The promise internally manages state changes pending, depressing, and Rejected, and changes the state by triggering resolve() and reject() in the construction. This triggers the callback function in.then(), which returns a Promise object for chain-calling.
2, Promise benefits: Asynchronous programming, solve callback hell.
Disadvantages: 1. Once a promise is executed, it cannot be stopped. If you want to stop a promise, resolve() and reject() will remain pending
4, promise API
then
catch
Promise.reject
Promise.resolve
Promise.all
Promise.race
14. Async functions and await
The async Function declaration is used to define an asynchronous function that returns an AsyncFunction object. An asynchronous function is a function that executes asynchronously through an event loop and returns its result with an implicit Promise. Return a Promise object.
Async functions may have await expressions, which cause the async function to pause, wait for the Promise result, and then resume the async function and return resolved. Note: await can only be used in async
15. Call, apply, bind
Similarity: Both can change the this pointer inside a function
Call and apply call functions and change the “this” pointer inside the function. Bind does not call the function
2. Call and apply pass different parameters. Call passes aru1,aru2.. Form. Apply must array form [arg]
Main application scenarios:
1. Call often does inheritance
2. Apply is often associated with arrays, such as using mathematical objects to achieve the maximum and minimum values of arrays
3. Bind does not call a function, but can also change the this pointer, such as inside a timer
16.JS Event Loop
- All synchronization tasks are executed on the main thread, forming an execution stack.
- Whenever an asynchronous task has a result, an event is added to the event queue.
- Once all synchronization tasks in the execution stack are completed, the system fetches event execution from the event queue.
The main thread reads events from the event queue in a loop called an event loop.
17. Macro versus micro tasks
MacroTasks | Microtasks | |
---|---|---|
Who initiated | Host (Node, browser) | JS engine |
Specific events | 1. Script (can be understood as the outer synchronization code) 2. setTimeout/setInterval 3. UI rendering/UI Events 4. postMessage,MessageChannel 5. SetImmediate, I/O (Node.js) |
1. Promise 2. MutaionObserver 3. Object. Proxy Object substitution)4. Process.nexttick (node.js) |
Who first run | After running | First run |
Will a new Tick be triggered | will | Don’t |
18. What are the new ES6 features?
1. Different variable declarations: const and let
2. Template string
3. Arrow function
4. Deconstruct assignments
5. Classes and inheritance
19. Difference between arrow function and ordinary function
1. The arrow function is an anonymous function and cannot be used as a constructor
Arguments (); To solve
3. This of the arrow function always points to the parent context
4. Arrow functions cannot modify their this pointer directly through call(), apply(), or bind()
5. Arrow functions have no stereotype attributes
20. Deep and shallow copies
Shallow copy copies only Pointers to an object, not the object itself, and the old and new objects still share the same memory. But deep copy will create another identical object, the new object and the original object do not share memory, modify the new object will not change to the original object.
Four vue.
1. Vue bidirectional binding principle
Vue.js uses data hijacking combined with the subscriber-publisher pattern, using objec.defineProperty () to hijack getters and setters for individual properties. Messages are published to subscribers when data changes, triggering corresponding listening callbacks.
2. The advantages of vue
- Two-way data binding
- Component-based development Vue.js uses components to split various modules in a single page application into a single component. The final assembly
- Virtual DOM optimizes DOM rendering operations
- Light weight and very little efficiency
3. The principle of vueRouter
VueRouter principle: Update the view without rerequesting the page.
Hash mode: Fields following hash mode # have no effect on the backend and will not be loaded. How it works: Use the onHashchange event to listen for browser history.
History mode: The background needs to be configured correctly to return an index.html if the URL does not match the resource. How it works: History mode uses HTML5’s pushState() and replaceState() methods. These two methods apply to the browser history stack. So when the user does something like refresh the page, the browser still sends a request to the server. To avoid this, the implementation requires server support to redirect all routes to the root page
4. Vue lifecycle
1.beforeCreate: Created: Data and methods are accessible when a component instance is created. 3. BeforeMount: Before the DOM is mounted and the template is compiled. BeforeUpdate: before component updates 6. Updated: After component updates 7. BeforeDestory: before component is destroyed 8
Mounted and created can be used to request data or bind data to a DOM structure when the HTML structure is already created.
5. Component communication in vUE
Parent to Child: use props
Child to Parent: Parent = component plus @getMessage= “getVal” The child uses $emit to trigger events and the parent listens for events
Sibling components: first new Vue instance, emit() events on the instance, emit() events on the instance, emit() events on the instance, emit() events on the instance, on() events on the listener, and execute the corresponding function.
Vuex by value
6. style scoped
When scoped is used in style, the CSS in the style tag applies only to the current page. CSS does not apply to child components. You can use scoped in the style tag of child components to make one page correspond to its own CSS and avoid affecting other pages.
7. Vue computed is different from Watch
computed
- Support caching, only the dependent data changes, will be recalculated
- Asynchronism is not supported. It does not work when there is asynchronous operation in computed, and data changes cannot be monitored
- Computed attribute values are cached by default, and computed attributes are cached based on their reactive dependencies, that is, values computed from the data declared in data or passed by the parent component
- If a property is computed by something else, that property depends on something else, it’s a many-to-one or one-to-one, usually computed.
- . If the computed attribute value is a function, the default is to use the GET method; The return value of the function is the property value of the property; In computed, attributes have a GET and a set method, which are called when data changes.
watch
-
Does not support cache, data change, will directly trigger the corresponding operation;
-
Watch supports asynchrony;
-
The listening function takes two arguments, the first of which is the latest value; The second argument is the value before input;
-
When an attribute changes, you need to perform the corresponding operation. A couple more;
-
The listening data must be the data declared in data or passed by the parent component in props. When the data changes, other operations are triggered. The function takes two arguments,
Immediate: The callback function is executed immediately after the component is loaded.
Deep: Used for complex types of data to detect changes in the value of an object, such as changes in the contents of the object in an array. Note that this is not required to listen for changes in the array. Note: Deep cannot listen for array changes or object additions, as in vUE array mutations, only when triggered in a responsive manner.
V. Computer networks
1.3 Handshakes and 4 waves
Three times handshake
- First time: The client sends a request to the server. The server knows that the client sends the request and receives it normally. SYN=1,seq=x
- Second: The server sends the packet to the client. The client knows that the packet can be sent and received properly, and the server can receive and send the packet properly. ACK=1,ack=x+1,SYN=1,seq=y
- Seq =x+1,ACK=1, ACK= Y +1 seq= X +1,ACK= Y +1
Four times to wave
- First: The client requests to disconnect the FIN. Seq = U
- Second: The server confirms the client’s disconnection request ACK (ACK = U +1, SEq = V)
- Third time: The FIN request is disconnected. Seq = W,ACK, ACK = U +1
- Fourth time: The client confirms the disconnected ACK of the server. ACK = W +1, SEq = U +1
6. Miscellaneous
1. Design patterns
-
Singleton pattern: Ensure that a class has only one instance and provide a global access point to it. For example, database connections in the framework
Singleton patterns are divided into hungriness and slacker.
Advantages: Only create an instance when the class is loaded. There is no need for multiple threads to create multiple instances, avoiding the problem of multi-thread synchronization. Disadvantages: This singleton can be created without being used, and memory is wasted when it is created after the class is loaded.
Lazy mode: Create instances at the right time, which may not be safe with multiple threads.
-
Js factory pattern: by using engineering methods instead of the new keyword. Encapsulate the created instance in a method, centralizing all instantiated code in one place to prevent code duplication.
The js factory mode is used to create objects. Usually a function passes in an Object, adds the parameters to the new Object, and returns the Object. Simple Factory pattern: Define a factory class that can return instances of different classes depending on the parameters. The created instances usually have a common parent class. Abstract classes, concrete implementation classes, factory classes, clients.
The normal factory pattern: first define the factory interface; then implement the factory class. Added more code to the client side. The normal factory method transfers the internal logic of a simple factory to the client code, calling the factory class create to create the product.
-
Observer mode: An object makes itself observable by adding a method. It sends messages to registered observers when observable objects change. For example, the implementation implements message push
2. The Typescript and javascript
Typescript is a superset of Javascript from Microsoft. Typescript requires data to be typed explicitly, whereas javascript does not. TypeScript provides compile-time static type checking through type annotations. Identify certain types of problems before code runs.
3. What’s the difference between const and readonly in TypeScript?
- Const can only be initialized at declaration time. Readonly can be initialized in a declaration or constructor.
- 2, const implies static, can not write static const; Readonly does not default to static. If necessary, you can write static readonly.
- 3. Const is a constant that is resolved statically at compile time (so its expression must be evaluated at compile time); Readonly is a constant that is dynamically resolved at runtime;
- 4. Const modifies a member of a class as well as a local variable inside a function. Readonly can only be used to modify members of a class.