What are the data types in Js
Basic types of
- String
- Number
- Boolean
- null
- undefined
- symbol
Reference types
- object
Talk about Http status codes
1** message, the server received the request and needs the requester to proceed with the operation (101, upgrade to websocket protocol) 2** successful, the operation was successfully received and processed (206, partial content, segmtioned transmission) 3** redirection, further operation required to complete the request (301,302 redirection; 304 Hit cache) 4** Client error, request contains syntax error or cannot complete request (401, requires authentication; 403, The server understands the client’s requirements, but is not allowed to access
Talking about Ajax status codes, does Ajax have to be asynchronous?
Ajax is not necessarily asynchronous and can be configured with the third parameter of the open method (default: true, asynchronous)
Status code:
0 – (uninitialized) The send() method has not been called. 1 – (loaded) The send() method has been called and the request is being sent. 2 – (loaded) The send() method is executing. 3 – (interactive) The response is being parsed
What is Ajax? Advantage? Disadvantage? What should we pay attention to?
Ajax is a standard for communicating with the background. The full name is Asynchronous Javascript And XML.
Advantage:
- You don’t need to refresh the page to request data, making the product faster, smaller, and friendlier
- The previous server tasks can be transferred to the client to handle, reduce the burden of the server, save bandwidth
- Browser support is good, no plugins required
Disadvantage:
- The browser rollback button is not supported
- Security is problematic and requests can be sent without the user’s knowledge
- Expose HTTP interaction details
- Support for search engines (web crawlers) is weak
- The program is not easy to debug
Questions to note:
- Browser compatibility issues, which jQuery and other libraries have covered for us
- Cross-domain problem, different domains are not allowed to access through Ajax, you can refer to teacher Ruan Yifeng’s cross-domain resource sharing CORS detailed explanation
- To be faster and search engine friendly, try not to use Ajax on the home page but server-side rendering (depending on the scene).
- Ajax is suitable for adding, deleting, modifying and querying operations
You write the printout of the following expression
1.toString() //Uncaught SyntaxError: Invalid or unexpected token
true.toString() //"true"
[].toString() //""
{}.toString() //Uncaught SyntaxError: Unexpected token .
null.toString() //Uncaught TypeError: Cannot read property 'toString' of null
undefined.toString() //Uncaught TypeError: Cannot read property 'toString' of undefined
NaN.toString() //"NaN"
Copy the code
These need to be memorized deliberately, where 1 and {} are grammatical errors. Null and undefined because there is no toString method, you can use call to borrow it (see the comment section for more details) :
1.. toString() //"1"
(1).toString() //"1"
Number(1).toString() //"1"
({}).toString() //[object Object]
Object.prototype.toString.call(null) //[object Null]
Object.prototype.toString.call(undefined) //[object Undefined]
Copy the code
Front-end performance optimization you know what
The content level
- Use the CDN
- Single domain name and multiple domain names: Single domain name reduces DNS lookup times, while multiple domain names increase the number of concurrent browser downloads. This requires tradeoffs. Generally, a domain contains no more than four resources.
- Avoid redirection (scenarios)
- Avoid 404
The network layer
- With caching, you can refer to another article, handwritten file servers, about front and back interactions
- File compression (tell the server what compression type you support via the response headers accept-encoding: gzip, deflate, BR)
- Loading on demand, extracting common code, tree-shaking, etc. (all can be done with WebPack)
- Reduce cookie size
- File merge, using CSS Sprite diagram to merge images
- Files are preloaded and images are loaded lazily
Render layers
- Js at the bottom, CSS at the top
- Reduced reflow and repaint
- Reducing DOM nodes
The code level
- Cache DOM nodes, reduce node lookup, CSS selector hierarchy optimization
- Reduce dom node operations
- Optimize loops by using breaks, continue, return, etc
- Things like event delegates, object pools, etc
Talk about reflow and repaint for browsers
Browser parsing process
- Parse the HTML to generate a DOM tree
- Parsing the CSS
- Apply CSS to the DOM tree and generate the Render tree (where each node is recorded with its style and location)
- Render the tree to the page
Reflow (back)
Reflow translates to backflow and refers to the page building the Render tree again. Reflux occurs at least once for every page, when the page is first loaded
In addition, reflow occurs when there are any changes in the page that might change the structure of the document (that is, changes in the relative or absolute positions of elements). The common ones are:
- Add or delete an element (except opacity:0, which is not delete)
- To change the size or position of an element
- Browser window changed (resize event triggered)
Repaint (redraw)
Repaint translates repaint, which can be likened to step 4 above, drawing a page according to the Render tree, with a lower performance cost than reflux. A redraw must occur every time the flow is reflow. In addition, the following operations (operations that do not affect the structure of the document, and those that do) can also be redrawn:
- Element color and transparency changed
- The text – align, etc
Browser optimization
It is not easy to know exactly which operations will cause which elements to flow back, and different browsers have different implementations. But it takes a long time to determine whether it is theirs because it involves a lot of calculation.
The browser has also been optimized to improve performance. The solution is to maintain a queue, cache all operations that need to be reflow and redrawn, and then execute them uniformly after a certain period of time. However, there are times when we need to get some location properties, and as soon as we call these apis, the browser has to compute the queue immediately to ensure that the data provided is accurate. For example:
- offsetTop, offsetLeft, offsetWidth, offsetHeight
- scrollTop/Left/Width/Height
- clientTop/Left/Width/Height
- width,height
- GetComputedStyle or currentStyle of IE
Pay attention to the problem
- Batch processing
- Use DocumentFragment for caching, which causes only one backflow
- Display: null for frequently operated elements, which only causes two backflows
- CloneNode and replaceChild, which only causes two backflows
- Instead of changing style frequently, change class
- Avoid calling properties such as offsetTop frequently and cache them before looping
- Absolutely locate elements with complex animations, otherwise it will cause frequent backflow of the parent element and a large number of subsequent elements
How do I remove the first space from a string?
//es6
' ab '.trim() //"ab"/ / regular' ab '.replace(/^\s*|\s*$/g,' ') / /"ab"
Copy the code
How do I get a query string in a URL
function queryUrlParameter(str) {
let obj = {}
let reg = /([^?=&#]+)=([^?=&#]+)/g;
str.replace(reg, function() {arguments[1]] = arguments[2]}hash
// reg = /#([^?&=#]+)/g
// if (reg.test(str)) {
// str.replace(reg, function () {
// obj.hash = arguments[1]
// })
// }
return obj
}
console.log(queryUrlParameter('http://www.baidu.com?a=1&b=2#12222')) //{ a: '1', b: '2'}
Copy the code
How to implement a deep copy, deep comparison
Deep copy
function clone(obj) {
if(obj == null || typeof obj ! = ='object') return obj
letNewObj = null // Time objects are specialif (obj.constructor === Date) {
newObj = new obj.constructor(obj)
} else {
newObj = obj.constructor()
}
for (let key in Object.getOwnPropertyDescriptors(obj)) {
newObj[key] = clone(obj[key])
}
return newObj
}
Copy the code
A deep comparison
function deepCompare(a, b){
if(a === null || typeof a ! = ='object'|| b === null || typeof b ! = ='object') {return a === b
}
const propsA = Object.getOwnPropertyDescriptors(a)
const propsB = Object.getOwnPropertyDescriptors(b)
if(Object.keys(propsA).length ! == Object.keys(propsB).length){return false
}
return Object.keys(propsA).every( key => deepCompare(a[key], b[key]))
}
Copy the code
How to achieve function throttling and shaking
The throttle
function throttle(fn, delay) {
delay = delay || 50
let statTime = 0
return function () {
statTime === 0 && fn.apply(this, arguments)
let currentTime = new Date()
if (currentTime - statTime > delay) {
fn.apply(this, arguments)
statTime = currentTime
}
}
}
letThrottleFn = throttle (fn) throttleFn () / / will only perform a throttleFn () throttleFn throttleFn () ()Copy the code
Image stabilization
function debounce(fn, delay) {
delay = delay || 50
let timer = null
return function () {
let self = this
clearTimeout(timer)
timer = setTimeout(fn.bind(self, arguments), delay); }}Copy the code
You write me a native bind method
Function.prototype._bind = function (context) {
let self = this
let args_1 = [].prototype.slice.call(arguments, 1)
return function () {
let args_2 = [].prototype.slice.call(arguments)
let args = args_1.concat(args_2)
return self.apply(context, args)
}
}
Copy the code
This is just a simple implementation of bind. If you are interested in learning more, refer to the use and implementation of the bind() method in Javascript
How do I flattens an array
function (ary) {
return ary.toString().split(', ')}Copy the code
This is an opportunistic approach (it will do for an interview), and if you’re interested, search for other implementations
How do I add, remove, move, and copy DOM nodes
create
- CreateTextNode () // Creates a text node
- CreateElement () // Creates the element node
- CreateDocumentFragment () // Creates a document fragment
operation
- The appendChild () / / increase
- The removeChild () / / delete
- The replaceChild () / / replace
- The insertBefore () / / insert
To find the
- getElementById()
- getElementByTagName()
- getElementByName()