routing

Routing allocates resources based on urls. The three front-end frameworks (Vue, React, Angular) use vue-router, react-Router, and Angular/Router to implement their own routing logic. But the underlying principle is the same

Hash routing

The core is a front-end route jump using location.hash and hashchange event, with a # on the link

Onhashchange = (e) => {console.log(e.oldurl, e.newurl); } // This triggers the hashchange callback location.hash = '#test';Copy the code

Features:

  1. # is part of the link and will not be taken to the server if it is not included in the request
  2. When the hash is refreshed, the page does not send requests to the server
  3. Each time a hashchange is performed, a record is added to the browser’s access history, so pages can be managed by moving the browser forward and backward

The history of routing

Route management is managed through the popState and History apis. Hisotry requests are sent to the server on each refresh, so the server should be aware of a backtracking operation

The History API has the following apis:

  1. Go can specify the number of returns, -1 to return the previous level
  2. History. forward forwards to the next route
  3. History. back Returns the last route
  4. PushState adds a stack to the route and jumps without refreshing the page
  5. ReplaceState Replaces the current route without refreshing the page

Features:

  1. Is a regular link
  2. Only pushState and replaceState do not refresh the page
  3. PopState cannot listen for pushState and replaceState events
  4. Refresh page for the server to request resources, resources do not exist 404, the server to bottom

The difference between

  1. Hash route links have hash and are purely client-side routes. The history link usually does not have hash and requires the server to perform bottom-bottom operations. Otherwise, the page will be 404
  2. Different apis. Hash routes listen for hashchange, history listens for popState, and History provides more apis for page jump management. Hash needs to manage these stacks itself
  3. Hash routing is not SEO friendly