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:
- # is part of the link and will not be taken to the server if it is not included in the request
- When the hash is refreshed, the page does not send requests to the server
- 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:
- Go can specify the number of returns, -1 to return the previous level
- History. forward forwards to the next route
- History. back Returns the last route
- PushState adds a stack to the route and jumps without refreshing the page
- ReplaceState Replaces the current route without refreshing the page
Features:
- Is a regular link
- Only pushState and replaceState do not refresh the page
- PopState cannot listen for pushState and replaceState events
- Refresh page for the server to request resources, resources do not exist 404, the server to bottom
The difference between
- 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
- 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
- Hash routing is not SEO friendly