The foundation of a few high frequency interview that ego sorts out, partial beginners, fresh year is unripe, feel useful dig a friend to give small love, thank!
HTML
What block level, inline elements do you know?
1. Block level elements: display: block/table, for example, div, p, ul, ol, table, and H1-H6
2. Inline elements: display: inline/inline-block, for example, span, input, button, and img
How to understand the semantics of HTML?
1. Make the code easier to understand and read
2. Make it easier for search engines to understand and read the code (SEO optimization)
What about the target attribute on the A tag?
1._self: the default value. No new page is displayed
2._blank: New page jump
Doctype? What are strict mode and promiscuous mode?
1.Doctype: The declaration is at the front of the document and tells the browser how to render the page. There are two modes, strict and promiscuous
2. Strict mode: Also known as standard mode, browsers parse code according to W3C standards
3. Promiscuous mode: Also known as weird mode, compatible mode, the browser in its own way to parse the code, backward compatibility, imitate the old site, in case it does not work
The difference between:
1. Does the width and height of the box model include padding and border
2.margin: 0 auto; Horizontal centering fails in promiscuous mode
3. In strict mode, the width and height of inline elements do not take effect, but in promisantine mode, they take effect
CSS
What is a float? What are the ways to clear a float?
Float: When a child element sets the float style, it leaves the flow of the document and stops when it encounters other floating elements or reaches the border of the parent element, causing a collapse in height
How to clear the float:
1. Add a blank label to the child element
2. Add overflow:hidden to parent element
3. Add pseudo-classes after and Zoom (clearFix) to parent element
What do you know about the box model and how to calculate its width?
The box model:
Box-sizing: content-box; Width does not include border and padding. Refer to W3C standard
Box-sizing: border-box; box-sizing: border-box; Width includes border, padding, weird mode
Width calculation:
OffsetWidth = border border + PADDING Inner border + width Content width excluding margins
What do you know about backflow and redrawing? When is backflow triggered?
Redraw: Without affecting the browser layout, the element style changes, the browser updates the element, and only the UI pixels are redrawn with little performance loss
Backflow: When the structure, size, or size of an element changes and the browser updates the element, the browser needs to recalculate the page and rearrange it, resulting in high performance costs
Trigger reflux:
1. First rendering of the page
2. Change of element position, size, size and structure
3. Change the font size
4. Add or delete the DOM
5. Browser window size changes
What are the four states and order of links?
Four states:
1. No Access 2. Yes Access 3
1.:link, not accessed
2. : active, activation
3. Hover the mouse
4. A. visited B. visited
Order:
1: the link, did not visit
2. : visited: accessible
3. Hover the mouse
4. : actived, activation
Weight comparison?
! Important > Inline Element > ID > class = Attribute > Tag > Wildcard
Horizontal center and vertical center?
Horizontal center:
Inline, text-align = center;
2. Block element, margin: 0 auto;
3. Absolute element, letf: 50% + margin-left negative
Vertical center:
1. Inline element, line-height = height;
2. Absolute element, top: 50% + margin-top negative
3. Absolute, transform(-50%, -50%);
4. Absolute element, letf, top, right, bottom are 0, margin: auto; (Ultimate solution)
What is a pseudo-element? What are the roles of :before and :after?
Pseudo-element: Creates a fake element inserted before or after the target element, which must have the content attribute or is invalid
:before — Inserted before the target element
:after — Inserted after the target element
The selector?
1.+ selector: Selects the first element immediately following the current one
2.:nth-child(n) Matches the NTH child of the parent element, n starting from 1
Use the formula nth-child(an + b), where n starts at 0 and n is the counter
How to hide elements?
1.display: none;
2.visibility: hidden;
3.opacity: 0;
What is BFC, forming conditions and application scenarios?
BFC: Block-level formatting context, a block of independently rendered areas, how can internal elements be rendered without affecting elements outside the boundaries
Forming conditions:
1. Don’t float to none
2. The overflow is not visible
3. Display is flex or inline-block
4. Position is absolute or fixed
Application scenario:
1. Clear float (best way: overflow: hidden — most compatible)
Display: None, visibility:hidden, and opacity: 0?
Display: none 👇
DOM structure: Hides elements and does not take up space
Performance: Reflux is triggered and performance costs are high
Event listener: Listener events bound to elements are invalid
Inheritance: Child elements are not inherited
Visibility: hidden 👇
DOM structure: Hides elements and occupies space
Performance: Redraw is triggered with low performance cost
Event listener: Listener events bound to elements are invalid
Inheritance: Child elements are inherited and can be unhidden by using visibility:visible
Opacity: 0 👇
DOM structure: Hides elements and occupies space
Performance: Does not trigger backflow, redraw
Event listener: Listener events bound to elements are valid
Inheritance: The child element is inherited, but the opacity:1 setting cannot unhide the child element
Said the flex?
1. Flex -direction Main axis direction — horizontal and vertical
2. Center-content Specifies the alignment mode of the main axes: start, end, center, and sides
3. Align cross-axes — start, end, center, and sides
4. The flex – wrap a newline
5. Align-self the alignment of children on the cross axis — start, end, center, and sides
How do WE inherit line-height?
1. If it is a numeric value, it is directly inherited
2. If ratio, inherit the line-height x ratio of the child element
3. If percentage, inherit the parent element’s line-height x percentage
What’s the difference between link and @import?
1. Link can define Rel, RSS, etc. @import can only load CSS
2. Link can be dynamically imported using Js, @import cannot
3. Load the CSS. When the page is parsed to link, the CSS style will be loaded synchronously
Margin negative and vertical overlap?
Margin negative:
1. If margin-left is negative, the element itself moves to the left
If margin-top is negative, the element itself moves upward
Margin-right negative: the element on the right is moved to the left, and the element itself is not affected
Margin-bottom negative: The elements below are moved up, and the elements themselves are not affected
Margin Vertical overlap:
Margin-top and margin-bottom will overlap each other, and the larger one will override the smaller one. The blank label will be overlapped (ignored).
What about position?
1. Position: static Position. Left, top, bottom, and right do not take effect
When the element is moved by top, bottom, right, or left, the element still occupies the original space whether or not it is moved
3. Position: Absolute positioning, according to the nearest level of positioning elements, out of the document flow, does not occupy the original space
4. Position: fixed positioning, relative to the browser window, out of the document stream, not always with body
The positioning element of the last layer: look up the parent element until the parent is the positioning element (Relative, Absolute, fixed, body), if not found, then the body is found
What are REM and EM? What are some common responsive layout solutions? What is a vw/vh?
Rem: the unit of relative length, font-size relative to the root element
Em: a unit of relative length, font-size relative to the parent element
Common responsive layout schemes:
1. Font size of REM relative to the root element
2.@media-query Media query, set the root element to the width of the screen
Vw: 1/100 of the width of the web viewport
Vh: 1/100 of the viewport height
Window. innerHeight: Viewport height: the height of the web page without the top and bottom of the browser
Z – the index function?
The higher the value, the higher the level. If the value is negative, it will be overwritten by the normal document flow
HTTP and HTTPS
HTTP concept?
Hypertext Transfer Protocol (HYPERtext Transfer Protocol) is the standard for client and server requests and responses. It is used to transfer hypertext from a WWW server to a local browser. It can make the browser more efficient and reduce network traffic
The cache?
What is caching?
Browser requests to the server, the server receives the request, to return to the corresponding content, the next time to send the same request, the content of the server response did not change, I don’t need to return the same content, but the browser directly to the local cache lookup, which reduces network request, to achieve a performance optimization
Why is caching needed?
Reduce network requests to optimize performance
What resources can be cached?
Static resources (JS/CSS/IMG…)
What is forced caching?
The cache-control in the response headers
Mandatory cache: The browser sends a request to the server for the first time. The server receives the request and determines whether the requested resource can be cached. If it can, it assigns a cache-control identifier and returns it to the browser
Cache to local storage. When the browser requests again, it will directly go to the local storage to reduce the number of network requests (the cache is not expired)
HTTP request mode?
1) GET access to
(2) POST to create
(3) PUT the update
(4) DELETE DELETE
⑤ OPTION pre-request
6. The HEAD
What is negotiation cache?
Etag/last-modified in Response headers
Negotiation cache: first requests to the server, the browser server returns resources and resource identifier, when a browser requests again, with a resource identifier, server compare whether the resource identifier is the same as last time return, if consistent returns 304 unchanged (resources), otherwise returns 200 and new resource identifier (cache expiration)
There are two types of resource identifiers: last-modified/Etag (Etag is preferred when co-existing)
The common HEADERS in HTTP?
Request header and Response header👇
The Request header:
① Accept Indicates the data format accepted by the browser
② accept-encoding Indicates the compression algorithm that can be accepted by the browser
③ accept-language Indicates the Language that the browser can Accept
④ Connection keep-alive A TCP Connection can be used repeatedly
(5) the Host domain name
6 Cookies
⑦ User-agent UA browser information
⑧ Content-type Specifies the Type of data sent by the browser
Response header:
① Content-type Specifies the Type of data returned by the server
② Content-length Specifies the size of the data returned by the server
③ Content-encoding Specifies the compression algorithm returned by the server
④ Set-cookies The Cookies of the server are modified
What’s the difference between HTTP and HTTPS?
① The connection mode is different, and the port is different. One is port 80, and the other is port 443
② HTTP, hypertext transfer protocol, plaintext transmission, while HTTPS is a secure SSL encryption transfer protocol
③ For HTTPS, you need to apply for a certificate from a certificate authority
(4) HTTP is a stateless connection, which means that packets are sent, transmitted, and received mutually
HTTP status code?
(1) 200 success
② 201 Resources have been created
③ 301 permanent redirection
④ 302 Temporary redirect
⑤ The 304 resource is not modified
⑥ 403 No permission
⑦ 404 Resource not found
⑧ 500 Server error
⑨ 504 The gateway times out
What’s the difference between GET and POST?
1. The transmission mode is different. The GET transmission is on the URL, while the POST transmission is in the request body
2. Security is different, because POST transmits data in the request body, which is relatively safe, while GET transmits data in the URL, which may be found in the browser’s history record and cache
3. The data type is different. The data transmitted by GET can only be ASCII characters, while the data transmitted by POST is unlimited
4. Browser refresh and rollback, get is harmless, but POST may be submitted again, resulting in duplication
HTTPS concept?
The security-oriented HTTP channel ensures the security of the transmission process through transmission encryption and identity authentication on the basis of HTTP
Pros and cons of HTTPS?
Secure, but the encryption scope is limited, when attacked by hackers, does not take effect, in the handshake phase is not as efficient as HTTP, more time-consuming
What is the difference between TCP and UDP?
1.TCP is connection-oriented, while UDP is connectionless
2.TCP is a reliable transport service, while UDP is unreliable
3.TCP is byte stream oriented, while UDP is packet oriented
4. The TCP header is 20 bytes, while the UDP header is only 8 bytes
5.TCP is one-to-one, while UDP is one-to-one or one-to-many
JavaScript
Closure?
What are closures?
A closure is a function that has access to variables in the scope of another function
What causes closures?
The presence of an outer – scoped reference to an inner function results in a closure
3. What do closures do?
① Privatize function attributes and methods
(2) Protect the private variables of the function from external interference
Fourth, closure application scenarios?
① Functions are passed as arguments
② The function is returned as a return value
③ IIFE (self-executing function)
(4) Loop assignment
⑤ Use the callback function
Shake and throttling?
Anti-shaking: The change event is triggered only when the user suspends or stops input
Throttling: frequent input, frequent operation, triggered at a continuous frequency
What is the difference between function declaration and function expression?
1. Function declarations are preloaded before code execution, similar to variable promotion
2. Function expressions are not preloaded
Function a() {… }
Const a = function () {… }
When to use third and second class?
=== Compares values and types without casting
== Only the value is compared, type conversion occurs
Use === for everything except == null
== null –> === null || === undefined
What are macro tasks and microtasks? What’s the difference?
Macro tasks: setTimeout, setInterval, Ajax event, DOM event
Microtasks: Promise, async await
The difference between:
1. Macro tasks are defined by the browser, and microtasks are defined by ES6
2. Macro tasks are executed after DOM rendering, while microtasks are executed before DOM rendering
3. Microtasks are executed earlier than macro tasks
What is a callback function? Examples?
Callback function: a pointer to a function that is passed as an argument to another function is called when the function to which the pointer points is called
For example:
const a = function () {console.log(1); }; const b = function (a) {a(); }; b();Copy the code
Logical judgment?
&& Returns a services variable
Return to a truly variable | |
Three features of object orientation?
1) encapsulation
(2) inheritance
(3) polymorphism
What is a memory leak? What are some common memory leak operations?
Memory leak: Waste of memory that is no longer used due to negligence or error
Common operations for memory leaks:
1. The closure
2. Global variables
3. Forgotten timers and callbacks
4. Circular references (references to DOM elements are not cleared in time and still exist)
What are the three design patterns you know?
1. Singleton mode 👇
Concept: To ensure that there is only one instance of a class, it is generally determined whether the instance exists. If it exists, it is returned directly. Otherwise, it is created first and then returned
Function:
1. Communication between modules
2. Ensure that the objects of a class are unique
3. Prevent variable contamination
2. Constructor mode 👇
Concept: Used to create objects of a specific type
Function:
1. Create objects of a specific type
2. Encapsulation of logic and services
3. Builder mode 👇
Concept: A complex logic or function is implemented step by step through a structured division of labor
Function:
1. Distribute to create a complex object or implement a complex function
2. Decouple the encapsulation process so that you do not need to pay attention to the creation details
Depth copy?
Shallow copy:
let a = { address: { city: 'beijing' } };
let b = a;
b.address.city = 'shenzhen';
console.log(a.address.city); // shenzhen;
Copy the code
Deep copy: when a is assigned to b, a does not change when B changes, and is independent of each other
Event bubble, event capture, event delegate?
Event bubble: Microsoft presented
Event capture: Netscape presented
Both solve the problem of the flow of events (the order in which events occur) in the page
Example:
<div id="outer"> <p id="inner">Click me! </p></div>Copy the code
In this code, if both elements have a click handler, how do you know which function is triggered first?
Event bubble: Events occur from the innermost element and propagate up to the Document object
Example click occurs in p -> div -> body -> HTML -> document
Event capture: Events occur from the outermost layer and propagate down to a specific element
Example click order: document -> HTML -> body -> div -> p
The three event phases are in sequence: Capture > Target > bubble
Target stage: The event reaches the target object, the event is triggered, if the event does not allow bubbling, the event will stop propagation
Event bubble and event capture process figure: 1-5 is the capture process, 5-6 is the target phase, and 6-10 is the bubble phase
—————
Prevent bubbling events:
StopPropagation () –> < span style = “word-break: break-word
2. Return false in the event handler –> Note: preventing bubbling also prevents the default event
Prevent default events:
1. event.preventDefault()
2. return false
—————
Event delegate: to delegate the event bound to the child element to the parent element. The parent element is responsible for event listening and judging whether the match is the target element when executing the event
How it works: Based on event bubbles
Advantages: Saves memory usage and reduces event registration
Application scenario: Infinite drop-down list of images, listening for each image click (multiple child elements, listening for click events)
Application scenario solutions: 1. Event proxy 2. Get trigger element 3 with E.t. get. Use matches to determine whether it is a trigger element
—————
Dom2-level events specify that the event flow supports both the event capture phase and the event bubble phase, and you can use addEventListener to process which phase the event is in
AddEventListener: Used to bind an event handler to a specific element
Syntax: e.addeventListener (event, function, useCapture)
Event: a string specifying the event name without the “on” prefix
Function: Must, specifies the function to be executed when the event is fired
UseCapture: Optional 1.true- the function is executed during the capture phase 2.false- Default, the function is executed during the bubble phase
JS basic data types and complex data types?
Basic data types:
1.Null
2.Undefined
3.String
4.Number
5.Boolean
6.BigInt
7.Symbol
Complex data types:
1.Object (Function, Array, Object, Date, RegExp)
What’s the difference between synchronous and asynchronous?
1.JS is single threaded, synchronizing code line by line execution
2. Synchronization blocks code execution
3. Asynchrony does not block the execution of the code (synchronous code is executed before asynchronous code is executed)
What about prototypes and prototype chains?
Prototype:
1. All reference types have an implicit stereotype attribute, __proto__, whose value is a normal object
2. All functions have an explicit prototype property, whose value is a normal object
3. The implicit prototype for all reference types __proto__ refers to its constructor’s explicit prototype
The prototype chain:
When accessing properties of an object instance, the current object instance is usually looked up first, if not found, then
Look for its implicit prototype __proto__, i.e. its constructor’s display prototype, as in
If not, look up the constructor’s implicit prototype __proto__.
So you go up layer by layer, and you form a chain
If null is not found, return undefined
2.object.prototype.__proto__ === null
What’s the difference between value types and reference types?
Value type:
let a = 100; let b = a; b = 200; console.log(a); // 100 console.log(b); / / 200Copy the code
Reference type:
let a = { city: 'beijing' };
let b = a;
b.city = 'shenzhen';
console.log(a); // { city: 'shenzhen' };
Copy the code
Value types: stored in the stack, bottom-up, small memory, value types: undefined, String, Number, Boolean, Symbol
Reference types: They are stored in the heap from top to bottom and occupy a large amount of memory. Reference types include Null, Object, Function, Regexp, and Array
How do I redirect to another page?
1.location.replace();
2.location.href();
What is scope? What are the types of scopes? What are the scoped lookup rules?
Scope: Represents the legal scope within which a variable can be used
Type:
1. Global Scope — The current variable is valid globally
2. Function scope — The current variable is only valid inside the function
3. Block-level scope — The current variable is valid only within a block
Scoped search rules:
1. A variable is not defined in the current scope, but is used
2. Search the upper scope layer by layer until it is found
3. If it is not found in the global scope, error XXX is not defined is reported
What is the difference between bind, call and apply?
Common: The function of all three is to change the direction of this
The difference between:
1. The first argument to call is the target object to which this refers, followed by a list of arguments, separated by commas
2. The first argument is the target object to which this refers, and the second argument is the array
Non-strict mode: if the first argument is not passed or is null or undefined, this refers to the window object. If a character, number, or Boolean value is passed, this refers to the value passed
Strict mode: this refers to whatever the first argument is passed, including null and undefined, or undefined if not passed
3. Bind returns a function that needs to be called, whereas call and apply execute immediately
Const, var, let
1. Var is an ES5 syntax, const and let are an ES6 syntax, var is a variable increment
2. Const, let has block-level scope, var does not
3. Var and let declare variables, while const declares constants.
What is the EventLoop? What’s the process?
EventLoop: Event polling, asynchronous based on callback functions, and EventLoop is the implementation principle of asynchronous callback
Process:
1.Js is single threaded, synchronized code is executed line by line on the call stack
2. When you encounter an asynchronous task, record it and wait
3. When the time comes, put the callback function into the queue
4. After synchronous code execution, clear the call stack and start EventLoop
5.EventLoop queries and retrieves the call function queue. If there is a function, it is put into the call stack for execution, and the call stack is cleared
6. Keep looking for it
ForEach, for in, for of?
ForEach: iterates over a group/array of objects without using a break, continue, return statement,
The first parameter value, the second parameter index, and the third parameter source array
For in: iterates through groups or objects, taking indices (array) or objects (key),
But iterates over the properties defined on the display prototype to array.prototype.xxx,
Use object.hasownPrototype ()–[make sure it’s a property of the instance]
For-of: introduced by ES6, which can be used to iterate over Iterable data, only the elements of the collection itself, taking values
What is the instanceof? What data types can it determine?
Concept: Used to determine whether the display stereotype property of a constructor exists on the stereotype chain of an object instance
Example:
function Car(name) {this.name = name; } let car = new Car('baoma'); console.log(car instanceof Car); // true console.log(car instanceof Object); // trueCopy the code
Judge type: simple value type can not judge, reference type can, can not accurately judge function
let a = 'xxx'; let b = new String('xxx'); console.log(a instanceof String); // false: undefined console.log(a instanceof String); // true let c = 1; let d = new Nunber(1); console.log(c instanceof Number); // false: undefined console.log(d instanceof Number); // true let e = true; let f = new Boolean(true); console.log(e instanceof Boolean); // false: undefined console.log(f instanceof Boolean); // true let g = {}; let h = new Object(); console.log(g instanceof Object); // true console.log(h instanceof Object); // true let i = function () {}; console.log(i instanceof Function); // true console.log(i instanceof Object); // trueCopy the code
What is JSON?
1.JSON is a data format that is essentially a string
2.JSON syntax is consistent with JS object structure and is JS language friendly
3.window.Json is a global object
Json.parse () converts a JSON string to a JSON object,
Json.stringify () converts a JSON object to a JSON string
The execution of the new operator?
1. Create a new object
2. The implicit stereotype of the new object points to the display stereotype of the constructor
3. The this inside the constructor points to the new object
4. Execute the constructor
5. If the constructor returns a non-empty object, return that object, otherwise, return the newly created object
What’s the difference between Splice and Slice?
1. Splice — splice, an impure function that changes an array, returning an array of elements that have been clipped
First argument: Starting position (subscript)
The second parameter: length
The third parameter: the element to be spliced, instead of the cut
2. Slice — a pure function that does not change the array and returns the array with the elements cut out
First argument: Starting position (subscript)
Second argument: End position (subscript)
This points to?
1. Called as a normal function (this points to the window object)
2. Arrow function (this always points to its parent scope, no this itself)
3. Called as an object method (this refers to the current object instance, or to the window object if the method was written with setTimeOut. This method is triggered by setTimeOut itself)
4. Called as a class method (this refers to an object instance from new)
5. Bind, call, apply (this is changed to point to the target object passed in — first argument)
What value does this take, not when the function is defined, but when the function is executed
What data types can Typeof determine?
1. Be able to judge all basic data types
1.’string’
2.’number’
3.’boolean’
4.’undefined’
5.’symbol’
Two, can judge the function type
1.’function’
3. The reference type cannot be determined
1.null -> ‘object’
2.object -> ‘object’
3.array -> ‘object’
What’s the difference between undefined and null?
Similarities:
In the if condition, both are converted to false
Difference:
Undefined: value undefined, value type, Number(undefined) -> NaN
Null: Value defined, null, reference type, Number(NULL) -> 0
The difference between Window Load and Document Ready?
// load
1. window.addEventListener(‘load’)
The page is executed only after all resources, including videos and pictures, are loaded
// ready
2. document.addEventListener(‘DOMContentLoad’)
DOM rendering can be executed, then the video, image may not be loaded
ES6 and ES7
What is an extended operator?
Used to extract traversable properties from a parameter object and shallow copy them to the current object
Array. The from ()?
Creates a new, shallow copy of the array instance from the array or object array
Example:
Array.from('abc'); // ["a", "b", "c"] Array.from(new Set(['a', 'b', 'a'])); // ["a", "b"] Array.from(new Map([[1, 2], [3, 4]])); / / [[1, 2], [3, 4]] function a () {return Array. The from (the arguments) / / [1, 2, 3]} a (1, 2, 3);Copy the code
Iterable?
ES6 introduces the new Iterable type in order to unify the collection types
Iterable: This type is available for… Of traversal. Arrays, sets, and maps are of this type
The Map and the Set?
Note: the key of a JavaScript normal object {} can only be of the underlying data type, and any key passed in is converted to string
ES6 Added Set and Map
Application scenario:
1. De-duplicate the Set array
2. Map array to new array/data store
———-
Map: a set of key-value pair structures that Map an array to a new array using any data type as a key
The new Map () to initialize the | | two-dimensional array [[key, value]]
Methods:
1. Add key-value to set
2. Has determines whether there is a key–Boolean
3. Get Obtains the value of the corresponding key
4. Delete Delete corresponding key and value–Boolean
5. Clear members
———-
Set: Similar to an array, member values are unique, there are no duplicate values, and casting does not occur
New to the Set () to initialize the | | array/value, value,…
Methods:
1. Add values (no duplicate values)
2. Has checks whether the value is a Set member
3. Delete Deletes a value. -Boolean
4. Clear members
Promise?
1. Three states
Pending: In the process, there is no result yet
Resolved: already solved
Rejected: has been rejected
pending -> resolved
pending -> rejected
The changing state is not reversible
2. Trigger function
Pending does not fire subsequent THEN and catch functions
Resolved triggers the subsequent THEN function
Rejected fires the subsequent catch function
3. Return to the status
The then function returns the Resolved state. If an error occurs, it returns the Rejected state
If the catch function returns to the Resolved state, it returns to the Rejected state
Async and await?
Async /await/promise
1. Async and await are the ultimate weapons to eliminate asynchronous callbacks
2. Promise is not mutually exclusive
3. Complement each other
Conclusion:
The async function (encapsulated promise) returns a Promise object
A. await B. promise C. await D. promise
The catch catches the exception. The catch catches the exception
④ async/await is just a syntactic sugar
git
Common operations?
1. Git checkout switch branch
2. Git checkout -b switch to the new branch
3. Git status Check the branch status
4. Git add. Place the updated branch in the staging area
5. Git commit -am record
6. Git push Origin commit branch to server
Git pull origin
8. Git merge branches
9. Git Branch
New features
New CSS3 features?
1.@font-face Load the font style
2. The selector
:last-child Selects the last child under the parent element
:nth-child(n) Selects the NTH child under the parent element
3. The animation animation
4. The transform 2 d transformation
5. The transition effect
6. Gradient ramp
7. Media inquiries
8. Shadow shadow
New ES6 features?
1.promise
2.for of
3. Deconstruct the assignment
4. Block level scope let-const
5. Template characters
6.Map/Set
7. Extension operators
New H5 features?
1. LocalStorage localstorage-sessionstorage
2. The semantic elements header/footer/section/article/nav
Canvas, vedio, audio
Performance optimization
Tell me the way you know?
There are two aspects of performance optimization: the loading process and the rendering process
Loading process:
1. Reduce resource size: compress code
2. Reduce the number of requests: code merge, server SSR rendering, caching
Use a faster network: CDN
Rendering process:
1. Put the CSS code in the head, and the JS code at the bottom of the body
2. Execute the JS code as early as possible, using DOMContentLoad
3. Lazy loading (image loading, component loading…)
4. Cache DOM queries
5. Frequent DOM operations to integrate elements and insert them into the DOM structure at one time
6. Throttling and damping
storage
What is the difference between localstorage-sessionstorage-cookies?
Cookies: a way for the server to record user status, which is set by the server and stored by the client. Each time the server initiates a request, the cookies are sent to the server. The storage size is 4KB, and the expiration time is specified by the expires attribute
SessionStorage: indicates the local storage mode provided by H5. The data saved in a session is valid only in the current session window and invalid when the session window is closed. The storage size is 5M and can only be shared by pages in the same window
LocalStorage: localStorage provided by H5. Unless manually deleted, the storage will never disappear. The storage size is 5M and can only be shared by pages of the same source
Cross domain
What is the same origin policy?
The current page and the server must be the same, that is, the protocol, domain name, and port must be the same
What do you know about Ajax?
Ajax: For requesting data asynchronously, with XMLHttpRequest at its core
Concept: Introduce a middle tier (Ajax engine) between client and server to make user actions and server responses asynchronous
Use: Create Ajax; Connect to the server; Send a request; Respond to the request
Advantages: Local update (no refresh state); Reduce server stress
Disadvantages: Slow page rendering when sending multiple Ajax requests; Security is low
Five states of Ajax?
XHR – readyState:
1.0 uninitialized, the send() method has not been called
2.1 Not loaded, send() method called, request in progress
3.2 The load is complete, the send() method has been executed, and the client has received the content returned by the server
4.3 Interaction, the response content is being resolved
5.4 Completed. The response content is resolved and can be invoked in the client
CORS is what?
CORS: Cross-domain resource sharing. It is a mechanism that uses HTTP headers on servers to share resources between clients and servers
Demo code:
response.setHeader('Accept-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
response.setHeader('Accept-Control-Allow-Headers', 'xxx');
response.setHeader('Accept-Control-Allow-Origin', '*');
Copy the code
What is the reason why fetch is sent twice?
Fetch first sends an option request, asks if the server supports the modified request header, and then sends the real request a second time if the server does
JSONP, principles, examples?
JSONP: The client requests JSON data from the server, the server receives the request, puts the response data in a callback function named and returns it to the client
How it works: Use script to bypass the restrictions of the same origin policy
Example:
The browser
What do you know about the browser kernel? And understanding it?
Browser kernel 👇
IE trident
Chrome blink
Opera blink
FireFox gecko
Safari webkit
The browser kernel is divided into two parts: rendering engine and JS engine 👇
1. Rendering engine: responsible for obtaining the content of the page, organizing information, calculating the display mode of the page, and then output on the display.
Different kernels of browsers parse web pages differently and render them differently
2.Js engine: parse and execute Js code to achieve the dynamic effect of web pages
Enter a URL into the page rendering process?
Loading process:
1.DNS resolution (domain name -> IP address)
2. The browser sends a request to the server based on the IP address
3. The server processes the request and returns the corresponding content to the browser
Rendering process:
1. Generate a DOM Tree according to the HTML code
2. Generate CSSOM based on the CSS code
3. Integrate DOM Tree and CSSOM into Render Tree
4. Start rendering the page according to the Render Tree
5. If encountered
6. Wait until Render Tree is complete
Engineering, modular concept
Front-end modularity?
Modularity: Objects with specific functions
Define a modular process:
1. Define modules (objects)
2. Export the module
3. Import modules
Function: Stores multiple independent function blocks with high reusability
Types: common. js, CMD, AMD
Common.js for server environments, CMD and AMD for browser environments
Front-end engineering?
1. Development tools
2. Development process
3. Development specifications
4. Develop the warehouse
5. Modular development
6. Component development
7. Project deployment
8. Optimize performance
Vue
Said the $nextTick?
1.Vue is asynchronous rendering
2. DOM does not render immediately after data changes
3.$nextTick fires after the DOM is rendered to get the latest DOM
this.$nextTick(() => {})
Copy the code
Life cycle call sequence containing parent and child components?
1. Mount phase
BeforeCreate (parent) -> Created(parent) -> beforeMount(parent) ->
BeforeCreate (child) -> Created(child) -> beforeMount(child) -> beforeMount(child)
Mounted -> Mounted
2. Update phase
BeforeUpdate (parent) -> beforeUpdate(child) -> Updated(child) -> Updated(parent)
3. Destruction phase
BeforeDestroy (parent) -> beforeDestroy(child) -> Destroyed(child) -> Destroyed(parent)
What about routing guards?
Route guard: Performs some authentication for route hops, such as login authentication
There are three types of route guards:
1. Global guard, router.beforeeach (to,from,next), set in main.js
BeforeEnter (to,from,next) is the same as router-. beforeEach(to,from,next), and only applies to the current route
3. Component exclusive guard, valid only for the current component,
router.beforeRouteEnter(to,from,next);
router.beforeRouteUpdate(to,from,next);
router.beforeRouteLeave(to,from,next);
Three parameters:
1. To Indicates the destination route
2. From Indicates the route from
3. Next determines whether to perform the next step
What about the route jump?
1.this.$route.push()
2.router-link
What about the life cycle?
Create/mount phase:
1. BeforeCreate: The instance is created, but data and methods are not initialized
2. Created: Instance, Data, and methods are initialized, but the template is not compiled
3. BeforeMount: The template is compiled and not mounted to the page
Mounted: The template has been mounted to a specified page container
Update phase:
5. BeforeUpdate: Called before the instance is updated, data is up to date, but the data on the page is not up to date (DOM is not rendered)
6. Updated: called after the instance is updated, data, page data are updated (DOM has been rendered)
Destruction stage:
7. BeforeDestroy: Called before the instance is destroyed, the instance is still available
8. Destroy: Called after the instance has been destroyed. Listen events, bind events have been removed, and child elements have been destroyed
How about bidirectional data binding?
The Vue bidirectional data binding principle is implemented through data hijacking combined with the publish-subscriber pattern
1. Data hijacking is implemented via object.defineProperty ()
2. The publishe-subscriber pattern is that Vue Data is used by multiple components. Each component that uses vue data registers its data in an array
How does the virtual DOM work?
1. The Js object simulates the real DOM tree and abstracts the real DOM tree
2. Diff algorithm to compare the differences between two virtual DOM trees
3. Path algorithm, which applies the differences between two virtual DOM objects to the real DOM tree
Custom components?
v-model
Use v-model=”name” on children of parent component
On a child component:
value="text" @click="$emit('click', $event.target.value)"
model: {prop:'text',event: 'click'}
props: {text: {type: 'String',default: () => {return ''}}}
Copy the code
What about communication between components?
1. Communication between parent and child components
Props: passes a property. The parent component passes a custom property to the child component on the child component, and the child component receives it through the props
Emit: the child component calls the method of the parent component, the parent component binds the custom method on the child component, the child component passes this. Emit: Emit a custom method. Emit a custom method. Emit a custom method. Emit a custom method
2. Communication between generational components
provide/inject
3. Communication between sibling components
Vue instance (new Vue()) includes on, on, on, emit, $off
$ON binds custom events
$emit calls custom events
$off uninstalls events in beforeDestroy
4.Vuex
What’s the difference between computed and Watch?
1.computed: calculates properties, cache according to the data object, depends on the property value of its property, the property value changes will be recalculated, has get and set methods
2. Watch: If the value of the dependent attribute is changed, a function will be triggered. By default, the shallow listener is listening on the value type, which can get oldVal. If the deep listener is listening on the value type, it needs to use deep+handler to listen on the reference type, which can not get oldVal
Why is data in a component a function?
When data is a function, each component creates a private data space, and each component maintains its own data. If data is an object, each component has one copy of data, and each change changes
What do you know about keep-alive?
1. Used to cache components
2.Vue performance optimization mode
3. Frequent switching, no need to repeat rendering
The parent component introduces three child components ABC. Component A is displayed when first loaded. You can switch components by pressing buttons, and they are all ↓
mounted: console.log(‘mounted’);
destroy: console.log(‘destroy’);
Under normal circumstances:
First render: A Mounted
A destroy B Mounted
C component: B Destroy C Mounted
Click A component: C Destroy A Mounted
Cycle…
After using keep-alive:
First render: A Mounted
Click B Component: B Mounted
Click C component: C Mounted
Click component A: No output, cached
The difference between MVVM and MVC?
The MVVM: 👇
M: Model, data Model (define data, modify, operate business logic)
V: UI component, which translates the data model into UI component for display
VM: ViewModel, listening to data changes, operation of business logic, handle user interaction, through two-way data binding to the View and Model to connect the bridge, View and Model is synchronous, developers only need to focus on the business logic, without the DOM operation
MVC:
M: Model, data Model (data and number processing method that encapsulates business logic)
V: View (render page)
C: controller (control process, operation business logic)
The difference between:
1. The Controller in MVC evolved into the ViewModel in MVVM
2.MVVM mainly solves: a large number of DOM operations in MVC, resulting in reduced page rendering performance and slow loading
3. In MVC, View and Model can interact directly with each other with high coupling degree, while in MVVM, View and Model do not interact directly with each other and synchronize through ViewModel with low coupling degree
4.MVVM uses data to drive view presentation rather than node operations
What’s the difference between v-show and V-IF?
Similarities: Both are used to show and hide elements
The difference between:
V-show: Use the display attribute to control the display and hiding of elements. The first rendering consumes a lot of performance, and the frequent switching consumes little performance. It is suitable for the scene where the elements are frequently switched
V-if: Controls the display and hiding of elements by adding or deleting DOM elements. It consumes little performance for the first rendering while consumes much performance for frequent switching. It is suitable for the scene where the elements are switched once
Said Vuex?
Vuex: indicates the state management mode
State: The unique source of data (data source). All Vuex data is stored in state (i.e. in memory).
Getter: Indicates the computed property of state. The type is computed. It is used for filtering data
Action: The method of processing data from mutation is asynchronized, and the View layer distributes the action through store.Dispatch
Mutation: Commit mutation processes data synchronously. Generally, a mutation is first committed, and a state is passed into the mutation, and the data is modified in the state. This is to record the history and track of each data modification for easy monitoring
Module: When a project is complex, each module has its own state, getter, Action, and mutation for easy management