JS interview question notes 6-Web API

Posted by ciciep on Tue, 12 Oct 2021 06:11:18 +0200

  • JS basics, specifying syntax (ECMA 262 standard)
  • JS Web API, API for web page operation (W3C standard)
  • The former is the basis of the latter, and the combination of the two can be really applied in practice
  • contain
    • DOM
    • BOM
    • Event binding
    • ajax
    • storage

DOM

  • DOM essence

    "Tree" (data structure) parsed from HTML file

  • DOM node operation

    Get DOM node

    • getElementById - element
    • getElementByTagName – collection
    • getElementByClassName - Collection
    • querySelectorAll – collection

    Attribute – modifying the html attribute will change the html structure

    • element.getAttribute('xxx')
    • element.setAttribute('xxx', 'yyy)

    property – modify the object properties, which will not be reflected in the html structure (try to use prop)

    • Manipulate its properties as js object properties
      eg: p.style.width = '100px'

    🔔 Both can cause DOM re rendering

  • DOM structure operation

    Add / insert node

    • document.createElement('yyy')
    • element.appendChild('xxx ') (can also be used as a mobile node)

    Get the child element list and get the parent element

    • element.childNodes
    • element.parentNode

    Delete child node

    • element.removeChild(xxx)
  • DOM performance

    • DOM operations are very expensive. Avoid frequent DOM operations
    • Cache DOM queries
    • Change frequent operation to one-time operation
    const list = document.querySelector('#list')
    
    // Create a document fragment that has not yet been inserted into the DOM tree
    const frag = document.createDocumentFragment()
    
    for (let i = 0; i < 10; i++) {
      const li = document.createElement('li')
      li.innerHTML = `List item ${i}`
    
      // Insert into document segment first
      frag.appendChild(li)
    }
    
    // After completion, it is uniformly inserted into the DOM structure
    list.appendChild(frag)
    

BOM

  • APIs

    navigator.userAgent – browser information

    screen.width/height – width and height

    location.href
    location.protocol – protocol
    location.host – domain name
    location.pathname – path
    location.search – query parameters
    location.hash – hash

    history.back – back
    history.forward – forward

event

  • Write a general event listening function

    // General event binding function
    function bindEvent(elem, type, fn) {
      elem.addEventListener(type, fn)
    }
    
    const btn1 = document.getElementById('btn1')
    bindEvent(btn1, 'click', (event) => {
      // event.target gets the triggered element
      // event.preventDefault() blocks the default behavior
    })
    
    // General event binding function (supports both general binding and proxy)
    function bindEvent(elem, type, selector, fn) {
      if (fn == null) {
        fn = selector
        selector = null
      }
      elem.addEventListener(type, (event) => {
        if (selector) {
          const target = event.target
          // Proxy binding
          if (target.matches(selector)) {
            // Does the element conform to the selector
            fn.call(target, event)
          }
        } else {
          // Normal binding
          fn.call(target, event)
        }
      })
    }
    
  • Describe the process of event bubbling

    • Tree structure based on DOM
    • Events bubble up along the trigger element
    • Application scenario: proxy
    const p1 = document.getElementById('p1')
    bindEvent(p1, 'click', (event) => {
      event.stopPropagation() // Stop bubbling
      console.log('activation')
    })
    const body = document.body
    bindEvent(body, 'click', (event) => {
      console.log('cancel')
    })
    
  • Event agent

    • Concise code
    • Reduce browser memory usage
    • Never abuse
    const div3 = document.getElementById('div3')
    bindEvent(div3, 'click', (event) => {
      event.preventDefault()
      const target = event.target
      if (target.nodeName === 'A') {
        alert(target.innerHTML)
      }
    })
    
  • Infinite drop-down picture list, how to listen for each picture click

    • Event agent
    • Get trigger elements with e.target
    • Judge whether to trigger elements with matches

Ajax

  • XMLHttpRequest

    // get request
    const xhr = new XMLHttpRequest()
    xhr.open('GET', '/api', true) // asynchronous
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.state === 200) {
          alert(xhr.responseText)
        }
      }
    }
    xhr.send(null)
    // post request
    xhr.send(JSON.stringify(postData))
    
  • Status code

    xhr.readyState

    • 0 - not initialized. The send method has not been called
    • 1 - load called send method, sending request
    • 2 - load completed, send method execution completed, and all response contents have been received
    • 3 - the interaction is parsing the response content
    • 4 - response content parsing is completed and can be called on the client

    xhr.status

    • 2xx - successful
    • 3xx - redirect
    • 4xx - client request error
    • 5xx - server side error
  • Cross domain

    Homology strategy

    • ajax request, the browser requires that the current web page and server must be homologous (secure)
    • Homology: protocol, domain name and port must be consistent

    Loading picture css js can ignore the homology policy

    • < img SRC = XXX / > can be used for statistical management, and third-party statistical services can be used
    • < link href = XXX / > CDN can be used
    • < script SRC = XXX > < / script > CDN can be used to realize JSONP

    Cross domain

    • All cross domains must be allowed and coordinated by the server side
    • Cross domain implementation without the permission of the server side indicates that the browser has vulnerabilities and dangerous signals
  • JSONP

    • script can bypass cross domain restrictions
    • The server can dynamically splice data and return as long as it meets the requirements of html format
    • script can obtain cross domain data as long as the server is willing to return

    Implementing JSONP with jQuery

    $.ajax({
      url: 'xxx',
      dataType: 'jsonp',
      jsonpCallback: 'callback',
      success: function (data) {
        console.log(data)
      },
    })
    
  • CORS - server settings http header

  • Handwritten Ajax (combined with Promise)

    function ajax(url) {
      const p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              resolve(JSON.parse(xhr.responseText))
            } else if (xhr.status === 404) {
              reject(new Error('404 not found'))
            }
          }
        }
        xhr.send(null)
      })
      return p
    }
    const url = '/api'
    ajax(url)
      .then((res) => console.log(res))
      .catch((err) => console.error(err))
    
  • ajax plug-ins commonly used in actual projects

    • jQuery
    • fetch
    • axios

storage

  • cookie

    • It is used for communication between browser and server
    • Borrowed to local storage
    • You can modify it with document.cookie =
      document.cookie is overwritten by the same key and appended by different keys

    Disadvantages:

    • Storage capacity: 4kb
    • http requests need to be sent to the server to increase the amount of requested data
    • It can only be modified with document.cookie =, which is too simple
  • localStorage sessionStorage

    • HTML5 is specially designed for storage, with a maximum storage capacity of 5M
    • API easy to use setItem getItem
    • It will not be sent with the http request

    difference

    • localStorage data is stored permanently unless code or manually deleted (use more)
    • sessionStorage data only exists in the current session. If the browser is closed, it will be cleared
  • cookie localStorage sessionStorage differences

    • capacity
    • API ease of use
    • Send with http request

Topics: Javascript