Front end interview questions

JS

What are basic data types in JS? What is a reference data type? difference?

  • Basic data types (stored on the stack): number, string, Boolean, undefined, null Symbol(es6 new)

  • Reference data type (stored in the heap and reference address of data stored in the stack): object, array, function, date, RegExp

How many ways to judge the data type?

  • typeof: typeof identifies all value types and functions, and determines whether they are reference types

    let a
    typeof a  // undefined    
    typeof '123'  // string
    typeof 123  // number
    typeof true  // boolean
    typeof Symbol()  // symbol
    typeof null  // object
    typeof function() {}  // function
    typeof console.log  // function
    // Use typeof to identify the reference type. All objects returned are objects, except functions
    typeof []  // object
    typeof {} // object
    
  • Instanceof: if the variable is an instance of a given reference type (identified according to its prototype chain), the instanceof operator will return true

    let obj = {}
    obj instanceof Array // false
    obj instanceof Object // true
    // It is found that the array is difficult to distinguish with instanceof
    [] instanceof Array  // true  
    [] instanceof Object // true
    // Detection array
    Array.isArray([])
    perhaps
    if (!Array.isArray) {
      Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
      }
    } 
    
  • constructor

  • Object.prototype.toString.call(): can distinguish null, string, boolean, number, undefined, array, function, object, date and math data types

    console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" 
    console.log(Object.prototype.toString.call(null)); // "[object Null]" 
    console.log(Object.prototype.toString.call(123)); // "[object Number]" 
    console.log(Object.prototype.toString.call("abc")); // "[object String]" 
    console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
    function fn() {
       console.log("ming");
     }
     var date = new Date();
     var arr = [1, 2, 3];
     var reg = /[hbc]at/gi;
    console.log(Object.prototype.toString.call(fn));// "[object Function]" 
    console.log(Object.prototype.toString.call(date));// "[object Date]" 
    console.log(Object.prototype.toString.call(arr)); // "[object Array]"
    console.log(Object.prototype.toString.call(reg));// "[object RegExp]"
    

==What's the difference between = = = and = =

  • ==: compare values only
  • ===: compare value types and value sizes

Object Copy

  • Shallow copy: a pointer is added to point to the existing memory address. If the original address changes, the shallow copied object will change accordingly
    Object. Assign(): object. Assign() copies the attribute value. If the attribute value of an object is a value type, the new object obtained through Object.assign({},srcObj) is a deep copy; If the attribute value is a reference type, it is actually a shallow copy for this object;

    function shallowCopy(obj) { // custom
      if(typeof obj !== 'object'){
        return obj
      }
      let newObj = Array.isArray(obj) ? [] : {}
      for(let key in obj) {
        if(obj.hasOwnProperty(key)){
           newObj[key] = obj[key]
        }
      }
      return newObj
    }
    
  • Deep copy: a pointer is added and a new memory is applied to make the increased pointer point to the new memory. If the value of the original object changes, the value of the deep copy will not change

    function deepCopy(obj) { // JSON.stringify
      return JSON.parse(JSON.stringify(obj))
    }
    function deepCopy(target, obj) { // Recursive function
      if(!obj) return
      if(typeof obj !== 'object'){ // //Not a direct return of an object
        return obj
      }
      let ret = target || []
      for (let key in obj) {
        // Property is an object, recursive
        if (obj[key] instanceof Object){
          ret[key] = obj[key].constructor=== Array ? []: {}
          deepCopy(ret[key], obj[key])
        } else {
          ret[key] = obj[key]
        }
      }
      return ret
    }
    

Array de duplication

// The value stored in set is unique. If duplicate data is stored, it will be filtered automatically
let arr = [1,1,1,3,4,5,2.5] 
let s = new Set(arr)  
// Array.from() creates a new, shallow copy of an array instance from a similar array or iteratable object
let newArr = Array.from(s)
console.log( newArr)  // [1, 3, 4, 5, 2.5]

// reduce()
let arr = [1,1,1,3,4,5,2.5] 
let newArr = arr.reduce((accumulator, currentValue) => {
  if(!accumulator.includes(currentValue)) {
     accumulator.push(currentValue)
  }
  return accumulator
}, [])

The difference between call, apply and bind

Function: change the direction of this when the function is running

  • Apply, call: call immediately, call the second parameter, pass the parameter list, and apply is the parameter array
  • bind: returns the corresponding function, so that it can be called later.
function add(c, d){ 
    return this.a + this.b + c + d; 
} 
let o = {a:1, b:3}; 
// Call immediate call parameter list
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 
// apply immediately calls the parameter array
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 
// bind returns the corresponding function, which is called later.
add.bind(o, 5, 7)(); // 1 + 3 + 5 + 7 = 16 

What is scope and scope chain?

  • Scope: Specifies the usable range of variables and functions

  • Scope chain: each function has a scope. When searching for variables or functions, you need to search from the local scope to the global scope in turn. The collection of these scopes is the scope chain

Event bubbling / event capture, DOM, event flow, event broker

  • Event bubbling: it is executed from bottom to top (son to ancestor). The third attribute in addEventListener is set to false (default)

  • Event capture: it is executed from top to bottom (ancestry to son), and the third attribute in addEventListener is set to true. DOM event goes through the phase

  • DOM event goes through three stages: when a DOM event is triggered, it is not triggered only once on the triggered object, but goes through three stages. They are

    • Flow from the root node of the document to the target object (capture phase)
    • Then triggered on the target object (target phase)
    • Then go back to the root node of the document (bubble phase) details
  • Event agent: the event is implemented mainly according to the bubbling mechanism. It is not directly bound to an element, but to the parent element of the element. When triggering an event (such as' click '), the statement after the event is triggered is executed through condition judgment

    advantage:

  • Greatly reduce memory consumption and event registration

  • The new element implements dynamic binding events

  • Make code more concise

What is the difference between var, let and const?

  • var: variable declaration is in advance, and there is no block level scope. It can be declared repeatedly (causing variable coverage and no error)

  • let: variable declaration will not be advanced. It has block level scope and cannot be repeated. Declared variables can be modified

     for (let i = 0; i < 10; i++) { 
       // The current i is only valid in this cycle, that is, i is actually a newly generated variable in each cycle.
       // The variable i declared with let only acts inside the loop body without external interference.
       setTimeout(function() {
          console.log(i);    // 0  1  2  3  4  5  6  7  8 9                        
        }, 0);
      }
    
  • const: variable declaration is not in advance, has block level scope, cannot be repeated, and the declared variable cannot be modified

Arrow function

Different from ordinary functions: the arrow function does not have its own this value. The this used in the arrow function comes from the function scope chain. Its value follows the same rules as ordinary variables and looks up layer by layer in the function scope chain.
Advantages: the arrow function greatly simplifies the value rule of this, and there is no need to store this with that variable. For example, it solves the problem of this pointing of anonymous functions and setTimeout and setInterval

window.name1 = 'me'
let test = {
  name1: 'aley',
  say: function () {
    console.log(this.name1) // aley
    let self = this
    // Anonymous function
    return function () {
       // this => window  self => test
       console.log('self', self.name1) // aley
       console.log('this', this.name1) // me
    }()
  },
  say1: function() {
    console.log(this.name1) // aley
    setTimeout(() => {
        // This = > the arrow function of the test object does not have its own this value. Look up the upper scope
        console.log(this.name1) // aley
    }, 50)
  }
}
test.say()
test.say1()

Function parameters (Default Parameters)

  • Default parameter: the default parameter in ES6 is directly assigned in the function parameter
  • rest parameter
    ES6 introduces the rest parameter (in the form of... Variable name) to obtain the redundant parameters of the function instead of the arguments object in the function parameters. The variable matched with the rest parameter is an array, which puts the redundant parameters into the array
    function f1(x,y=5,z=y, ...args) {
    console.log(x,y,z) // 1,4,5 
    console.log(args) // [6]
    }
    f1(1,4,5,6)   
    
    Note: there can be no other parameters after the rest parameter

Extension operator (spread)

Extension operator: we can understand it as the inverse operation of rest parameters, converting an array into a comma separated sequence of parameters

function sum(x=1,y=2,z=3) {
   return x + y + z 
}
let data= [2,4,5]
console.log(sum(...data))  // ... data returns 2,4,5 extension operators

Deconstructing assignment

Deconstruction: you can quickly obtain elements or attributes in arrays or objects without using traditional methods such as arr[x] or obj[key] to assign values
Note: all traversable can be deconstructed and assigned, such as array, object, string, etc
Deconstruction assignment form: simple variable assignment object attribute assignment loop body assignment rest variable deconstruction assignment

  • array

    let arr = ['a', 'b', 'c', d]
    
    // Simple variable assignment
    // Take the first and third items
    let [a,,c] = arr
    console.log(a,c) // a c
    let str = 'abcd'
    let [a,,c] = str
    console.log(a,c) // a c
    
    // rest variable deconstruction assignment
    let arr = [1,2,3,4,5,6,7,8]
    let [a,,c,...rest] = arr
    console.log(a,c,rest) // 1 3 [4,5,6,7,8]
    
    // Object attribute assignment
    let user = {name: 's', age: '18'};
    [user.name, user.age] = ['d', '12']
    console.log(user) // {name: 'd', age: '12'}
    
    // Loop assignment
    // The Object.entries() method returns an array of key value pairs of enumerable properties of a given object
    for (let [k,v] of Object.entries(user)) {
     console.log(k,v) // name d age 12
    }
    
  • object

    let obj = {
      menu: 'aley',
      weight: '80',
      height: 154
    }
    let {menu, weight = 88, height} = obj // aley 80 154
    let {menu, ...rest} = obj  // aley {weight:80, height:154}
    
    // Nested data
    let options = {
      size: {
        width: 40,
        height: 80
     },
     items: ['Cake', 'Donut'],
     extra: true
    }
    let {size: {width,height}, items: [,item2]} = options
    console.log(width,height,item2) // 40 80 Donut
    

Differences between ES6 and commonjs

  • commonjs module outputs a copy of the value, while ES6 outputs a reference to the value
  • commonjs is loaded at run time and is an object. ES6 is loaded at compile time and is a code block
  • This in commonjs points to the current module, and this in ES6 points to undefined

JS module

Why use modularity: prevent naming conflicts / better separation, load on demand / better reusability / higher maintainability
Modular method: ES6/CommonJs/CMD

What is the difference between exports and module.exports?

Single thread / synchronous / asynchronous / Event Loop/Promise

Single thread: only one thing can be done at a time. The designer of JS language realizes this problem and divides all tasks into two types: synchronous tasks (hindering the execution of events) and asynchronous tasks (not hindering the execution of events)
Single thread reason: avoid DOM rendering conflict (the browser needs to render the DOM, and js can modify the DOM structure. When js is executed, the browser DOM rendering will pause, and the two sections of js cannot be executed at the same time. Modifying the DOM will conflict. webworker supports multithreading, but cannot access the DOM)
Event loop: all synchronous tasks are executed by the main thread first, and asynchronous tasks are placed in the task queue first. After the synchronous tasks are executed, the function of polling the asynchronous queue is called event loop, which is also the operation mechanism of js

Promise proposed in ES6: solves the problem of ES5 callback hell
During new Promise, a status pending is returned, and the status is changed through the resolve and reject functions
Resolve pending - > fully rejected pending - > the status of rejected is irreversible

function loadScript(src) {
  return new Promise((resolve,reject) => {
     script = document.createElement('script')
     script.src = src
     script.onload = () => resolve(src)
     script.onError = (err) => reject(err)
     document.head.append(script)
  })
}
// call chaining 
loadScript('./1.js')
  .then(() => {
     return loadScript('./2.js')
   },(err) => {
     console.log(err)
   }).then(() => {
     loadScript('./3.js')
   }, (err) => {
     console.log(err)
   })
   
// catch
loadScript('./1.js')
  .then(() => {
     return loadScript('./2.js')
   }).then(() => {
     loadScript('./3.js')
   }).catch((err) => {
     console.log(err)
   })
All: Multiple Promise The instance is packaged into a new Promise example,At the same time, the return values of success and failure are different. When successful, a result array is returned, while when failed, the first result array is returned reject Value of failure status
const p1 = Promise.resolve(1)
const p2 = Promise.resolve(1)
const p3 = Promise.resolve(1)
Promise.all([p1,p2,p3]).then((val) => {
  console.log(val)  //[1, 1, 1] 
})

Race: competition mechanism,Who gets the result first,Return that result first,Whether the result itself is a successful state or a failed state
const p1 = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(1)  
    },1000)
  })
}
const p2 = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(0)  
    },0)
  })
}
// Competition mechanism, who comes first
Promise.race([p1(),p2()]).then((value) => {
    console.log(value) // 0
})

Process is the basic unit of resource allocation by CPU
Thread is the smallest unit of CPU scheduling. It is a unit that runs based on the process and shares the memory space of the process

What are macro tasks and micro tasks? How?

  • Macro tasks: script, setTimeOut, setInterval, postMessage, setImmediate
  • Micro tasks: promise.then,process.nextTick, Object.observe, MutationObserver
    Note: Promise is a synchronization task

Execution sequence

  • Execute macro task script,
  • After entering script, all synchronization tasks are executed by the main thread
  • Put all macro tasks into the macro task execution queue
  • Put all micro tasks into the micro task execution queue
  • Empty the micro task queue first,
  • Take another macro task, execute it, and then empty the micro task queue
  • Sequential cycle
setTimeout(() => {
  console.log('1');
  new Promise(function (resolve, reject) {
    console.log('2');
    setTimeout(() => {
      console.log('3');
    }, 0);
    resolve();
  }).then(function () {
    console.log('4')
  })
}, 0);
console.log('5'); 
setTimeout(() => {
  console.log('6');
}, 0);
new Promise(function (resolve, reject) {
  console.log('7');
  resolve();
}).then(function () {
  console.log('8')
}).catch(function () {
  console.log('9')
})
console.log('10');
results of enforcement: //5 7 10 8 1 2 4 6 3

Module import and export

In ES6, both export and export default can be used to export constants, functions, files, modules, etc; You can import it from other files or modules through import (constant / function / file / module name) from '*' and use it

Differences between export and export default:

  • In a file or module, there can be multiple exports, and there is only one export default;

  • Export through export. When importing, use import {}. This form is called export on demand; export default is not required;

  • Members exported using export must be received on demand using {} in strict accordance with the name at the time of export;

  • For members exported by export, if you want to receive them with a different variable name, you can use as as as alias;

    // export
    export let port = 3000;
    export function getAccounts(url) { ... }
    const obj = {
      name: 'aley',
      age: 18
    }
    export default obj
    
    // Import
    // Alias as
    import {port as v1, getAccounts} from ''
    import obj from ''
    

Memory leak? Why does it cause memory leaks? Garbage collection mechanism?

Memory leak: refers to that the memory that is no longer used is not released in time, resulting in the unavailability of this section of memory
Reason: we can no longer access an object through js, but the garbage collection mechanism thinks that the object is still being referenced. Therefore, the garbage collection mechanism will not release the object, resulting in that the block of memory can never be released. A little makes a lot, and the system will become more and more stuck and crash
There are four common memory leaks: global variables (global variables declared by var, equivalent to being mounted on window objects), timers that are not cleared, closures, and DOM element references that are not cleared
Garbage collection mechanism: intermittently and irregularly find variables that are no longer used, and release the memory they point to, so as to prevent memory leakage

What are the strategies of garbage collection mechanism?

  • Mark removal method:
  • Reference counting method: when a variable is declared and assigned a value of reference type, the count of the value is + 1. When the value is assigned to another variable, the count is + 1. When the value is replaced by other values, the count is - 1. When the count becomes 0, it indicates that the value cannot be accessed, and the garbage collection mechanism clears the object

Anti shake and throttling

Same point: it can prevent a function from being called with meaningless high frequency

difference:

  • Anti shake: the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated; In short, when an action is triggered continuously, it is executed only the last time
    Application scenario: input box change event / mobile phone number, email verification input verification / window size Resize. Just calculate the window size after the window adjustment is completed to prevent repeated rendering

    function debounce(fn, delay) {
      let timer = null
      // Function anti shake will wait for a period of time when executing the target method.
      //When the same method is executed again, if the previous scheduled task is not completed, clear will drop the scheduled task and retime
     if (timer) {
        clearTimeout(timer)
      }
     timer = setTimeout(() => {
       fn()
     }, delay)
    }
    debounce(function() {
      console.log('Anti shake')
    }, 500)
    
  • Throttling: it means that the function is executed only once in a specific time

    // Timer version
    function trottle(fn, delay) {
      let timer = null
      // If the timer exists, it returns, and then triggers after this event is executed
      if (timer) return
      timer = setTimeout(function() 
        fn()
        timer = null
       }, delay)
    }
    trottle(function() {
      console.log('throttle')
    }, 500)
    // Timestamp version
    function trottle(func, delay){
      let last = 0
      return () => {
        // +new Date() converts the data type to Number. If the conversion fails, NaN is returned
        // new Date().getTime() === new Date().valueOf() 
        const currentTime = + new Date()
        if(currentTime - last > delay) {
          func.apply(this, arguments);
         last = +new Date();
       }
     }
    }
    

closure

  • Closure: a function that can read the internal variables of other functions, so that external variables can call the internal variables of the function
  • Principle: Based on the rules of function variable scope chain and the reference counting rules of garbage collection mechanism
    • Reference calculation rule: if the reference of a variable is not 0, it will not be recycled by the garbage collection mechanism. Reference is called
    • Function variable scope chain rule: if there is no declared variable in the underlying scope, it will look up to the upper level, return if found, and keep looking until the window variable is found, and return undefined if not
  • advantage:
    • Avoid contamination of global variables
    • Want a variable to be stored in memory for a long time (CACHE variable)
    • Enables external to call variables inside a function
  • Disadvantages:
    • Memory leakage (consumption), do not abuse closures
    • Resident memory to increase memory usage
  • Applications: private variables, reserved i operations in the for loop, anti chattering and throttling, etc
function a() {
    var name = 'Shier'
    return function(){
        return name
    }
}
var b = a()
console.log(b())
Prototype and prototype chain

Prototype: JS stipulates that each constructor (declarative function) has a prototype (explicit prototype) Property refers to another object. All properties and methods of this object will be inherited by the instance of the constructor. The _proto_ _ofall instances point to the prototype of their constructor, which means that those invariant properties and methods can be defined directly on the prototype object
All properties and methods that need to be shared by instance objects are placed in this object; Those properties and methods that do not need to be shared are placed in the constructor.
Since all instance objects share the same prototype object, from the outside, the prototype object seems to be the prototype of the instance object, and the instance object seems to "inherit" the prototype object
es5: use constructor to simulate class
es6:class Is to use the constructor to declare the syntax sugar of the class and encapsulate the constructor once
Prototype chain: multiple__ proto__ The set formed becomes the prototype chain

HTTP

What happened after entering the url from the browser

  • DNS domain name resolution: first check the local hosts file to see if there is an ip address corresponding to the current domain name. If there is a direct request, it will be found in the local domain name server. If the local domain name server is not found, it will be found from the root domain name server. Finally, after finding the corresponding ip address, save the corresponding rules to the local hosts file
  • The browser communicates with the Web server according to the queried IP address (the communication protocol is http protocol), sends a request, and the Web server returns it to the browser in the form of response message. Note: the server may return 304 or 200 for processing
  • Browser rendering (the rendering engine parses html files, including CSS,JS, etc.)
    • When CSS is loaded, CSS will not block the parsing of the DOM tree, but will block the rendering of the DOM tree, and CSS will block the execution of the following JS

    • JS loading, JS loading will affect DOM parsing, because JS may delete and add nodes. If it is parsed before loading, the DOM tree must be parsed again, and the performance is poor. If you don't want to block the parsing of the DOM tree, you can add a defer or async tag to the script.

      • defer: DOM parsing will not be blocked. It will be run after DOM parsing is completed
      • async: DOM parsing will not be blocked. It will run immediately after the resource download is completed
    • DOM rendering and Render tree rendering

      • Get the html and parse it into a Dom tree
      • Parse css and form a cssom (css tree)
      • Layout: care about location and size, and layout again is also called reflow
      • painting
      • Combine cssom and dom into a render tree
      • Composite

Cross domain

Homology strategy: when ajax requests, the browser must require that the current web page and server must be homologous. The so-called homology means that the domain name, protocol and port are the same.
Cross domain solutions:

  • Cross domain resource sharing (CORS): post back the same source information in the access control allow origin header (if it is a public resource, you can post back *). For example: access control allow origin: http://www.laixiangran.cn (allow cross domain names) pure server to do it
  • JSONP cross domain: because the script tag is not affected by the browser's homology policy, it is allowed to reference resources across domains. Therefore, you can dynamically create a script tag and use the src attribute to cross domains, which is the basic principle of JSONP cross domain
  • Image Ping across domains: since img tags are not affected by the browser's homology policy, resources can be referenced across domains. Therefore, cross domains can be performed through the src attribute of img tags, which is the basic principle of image Ping across domains. It can be used for statistical management and third-party statistical services

Three handshakes and four handshakes

To communicate with each other, the client and server must confirm that the receiving and transmitting capabilities of both ends are normal

Describe the differences between localstorage, sessionstorage, cookie and session

  • localStorage: after closing the browser, the data is still retained, unless manually cleared; different tags of the same browser can share localStorage in the same source case; the storage size is only 5MB
  • sessionStorage: it is invalid after the browser or tag is closed. It is only available in the iframe of the current tag and the same source can be shared
  • Cookie: it is saved on the client side. Generally, the value is set by the back end, and the expiration time can be set. The storage size is only 4K. It is generally used to save the user's information. Under http, cookies are transmitted in clear text, which is less secure. document.cookie("name = data; expire = time")
  • session: session s are stored on the server. Sessions are generally used to track the state of users. Sessions are more secure and stored on the server. However, in order to improve the performance of the server, some information will be saved in cookie s

The difference between Get and Post

  • Parameter passing: get parameter passing, the parameter is in the url; post parameter passing, the parameter is in the request body;
  • Security: get is less secure; post is more secure; to be exact, both are not secure. They are transmitted in clear text and will be accessed when passing through the public network, whether url, header or body. To be secure, you need to use https
  • Parameter length: the length of the get parameter is limited and small; the length of the post parameter is unlimited

HTTP status code

Status code: a 3-digit code used to represent the response status of hypertext transfer protocol of web server

Status codeEnglish namedescribe
200OKThe request was successful
301Moved PermanentlyPermanent redirection. The requested resource has been permanently moved to the new URI, and the new information is returned, including the new URI
302FoundTemporary redirection, resources are temporarily moved, and the client should continue to use the old URI
304Server resources have not changedTells the browser that the requested resource can be retrieved from the cache
400Bad RequestThe syntax of the client request is incorrect and the server cannot understand it
401UnauthorizedRequest user authentication
403ForbiddenThe server understood the client's request but refused to execute it
404NOt FoundThe server cannot find resources (web pages) according to the request of the client, so as to improve the access speed of the website
500Internal Server ErrorAn internal server error prevented the request from being completed
502Bad GatewayThe server is temporarily unavailable, sometimes to prevent system overload
503Service UnavailableThe server cannot respond due to maintenance or overload. The server can provide a retry after header to tell the client when to try again.
504Gateway Timeoutgateway timeout

HTTP structure

What fields do HTTP headers have

http cache

What is xss? What is csrf?

  • xss script injection: you do not need to do any login authentication. It will inject scripts (possibly js, hmtl code blocks, etc.) into your page through legal operations (such as entering in url and comment box)
    defense
    • Encoding: HTML Entity encoding is performed on the data entered by the user. Characters are converted into escape characters. Encode is used to convert some characters such as $var, so that the final output result of the browser is the same
    • Filtering: remove user entered event related attributes.
  • csrf cross domain Request Forgery: visit B without exiting A website, and B uses A's cookie to access the server
    • Token: every time a user submits a form, it needs to bring a token (the forger cannot access it). If the token is illegal, the server will reject the request

Difference between https and http

Write an ajax

axios

import _ from 'lodash'
// Convert the parameters in the url into objects; Convert object to url parameter form
import qs from 'qs'
function ajaxMixin(url, {method='GET', params={}} = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    // get splice parameters
    if (method.toUpperCase() === 'GET'&& !_.isEmpty(params)) {
      url = `url?${qs.stringify(params)}`
    }
    // true, asynchronous
    xhr.open(method, url, true)
    xhr.onreadystatechange = function() {
      if (xhr.readystate === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.reponseText))
        } else if (xhr.status === 404) {
          reject('404 Not Fount')
        } else {
          reject()
        }
      }
    }
    if (method.toUpperCase() === 'POST') {
      xhr.send(JSON.stringify(params))
    } else {
      xhr.send(null)
    }
  })
}
// Splice address parameters
        if (!_.isNull(url) && !_.isEmpty(urlParams)) {
          url = url + '?' + qs.stringify(urlParams)
        }
        // GET request, splice request parameters
        if (method === 'GET' && !_.isEmpty(params)) {
          const wen = !_.isNull(url) && !_.isEmpty(urlParams) ? '&' : '?'
          url = url + wen + qs.stringify(params)
        }

Front end performance optimization

  1. Reduce the number of requests
  2. Download faster: reduce resource volume: compress code, such as webpack packaging code
  3. Faster rendering: css is placed in the head and js is placed at the bottom of the body
  4. Faster rendering: lazy loading (lazy loading of pictures, more sliding loading up)
  5. Anti shake throttle
  6. Optimize network connectivity
  7. Optimize resource loading
  8. Reduce redraw reflow
  9. webpack optimization

Keywords: Javascript node.js Ajax

Added by timski72 on Sun, 26 Sep 2021 11:41:43 +0300