When learning Vue-Router, I learned two modes of front-end routing. In this paper, I summarized the principles and application scenarios of front-end routing and the two modes.

Overview of Front-end Routing

What is routing

The concept of routing first appeared in the back end. Simply speaking, routing is a way to interact with the back end server. It is one of the functions of routing to request different resources and pages through different paths.

The birth of front-end routing

Front-end routing started with Ajax, and with Ajax, the user interaction didn’t have to refresh the page every time, resulting in a vastly improved experience. As technology evolved, simple asynchrony was no longer enough, so a more advanced experience of asynchrony emerged — SPA(single-page application). The emergence of SPA has greatly improved the interactive experience of WEB applications. In the process of interaction with the user, there is no need to refresh the page, and the data is also obtained asynchronously through Ajax, making the page display more smooth. However, since the user interaction in SPA is realized by changing the HTML content with JS, the URL of the page itself does not change, which leads to two problems:

  • SPA cannot remember the user’s operation record, no matter it is refresh, forward or backward, it cannot show the user’s real expectation.
  • Although there are various page display forms in SPA due to different businesses, there is only one URL, which is unfriendly to SEO and inconvenient to be included by search engines.

Front-end routing appears to solve the above problems.

What is front-end routing

To put it simply, it matches a special URL for each view display form in SPA while ensuring that there is only one HTML page and no page refresh or jump when interacting with the user. Refresh, forward, backward, and SEO are all done through this particular URL. To achieve this goal, we need to do the following two things:

  • Change the URL and prevent the browser from sending requests to the server.
  • You can listen for url changes

The following hash and History modes do this.

Hash pattern

The principle of

  • Early implementations of front-end routing were based on location.hash, where the value of location.hash was the content after # in the URL. The idea was to listen for the content after # to make Ajax requests for local updates without refreshing the entire page.
  • The hashchange event is used to listen for CHANGES in the URL. The hashchange event is triggered when the URL is changed by browsers moving forward or backward, by an A tag changing the URL, or by window.location changing the URL.

use

//html
<ul id="menu">
  <li>
    <a href="#index"</a> </li> <li> <a href="#news"> info </a> </li> <li> <a href="#user"> Personal center </a> </li> </ul> <div id="app"></div>

//js
function hashChange(e){
    let app = document.getElementById('app')
    switch (location.hash) {
      case '#index':
        app.innerHTML = '

This is home page content

'
break case '#news': app.innerHTML = '

This is news

'
break case '#user': app.innerHTML = '

This is personal central content

'
break default: app.innerHTML = '<h1>404</h1>' } } window.onhashchange = hashChange hashChange() Copy the code

advantages

  • Compatible with older browsers, Angular1.x and Vue use hash routing by default
  • Only the content before the # symbol is included in the request and sent to the back end, meaning that the back end does not return a 404 error even if it does not have full routing coverage
  • Changes to the hash value add a record to the browser’s access history, so switching the hash through the browser’s back and forward buttons overwrites the anchor location element

disadvantages

  • It is not very beautiful. There will be problems if the data transmitted after the # is complex

The History mode

The principle of

  • History provides pushState and replaceState methods to record the state of the route, which change the URL without causing a page refresh
  • History provides a popState event similar to the Hashchange event, but the popState event is a little different: A POPState event is triggered when a URL is changed forward or backward by the browser. A POPState event is not triggered when a URL is changed via pushState/replaceState or a tags. Fortunately, we can intercept calls to pushState/replaceState and a tag clicks to detect URL changes, so listening for URL changes is possible, but not as convenient as hashchange.
  • PushState (state, title, URL) and replaceState(state, title, URL) both accept the same three parameters.

use

//html
<ul id="menu">
  <li>
    <a href="/index"</a> </li> <li> <a href="/news"> info </a> </li> <li> <a href="/user"> Personal center </a> </li> </ul> <div id="app"></div>

//js
document.querySelector('#menu').addEventListener('click'.function (e) {
  if(e.target.nodeName ==='A'){
    e.preventDefault()
    let path = e.target.getAttribute('href'PushState ({}, {});' 'Render (path) render(path) render(path) render(path)function render(path) {
  let app = document.getElementById('app')
  switch (path) {
    case '/index':
      app.innerHTML = '

This is home page content

'
break case '/news': app.innerHTML = '

This is news

'
break case '/user': app.innerHTML = '

This is personal central content

'
break default: app.innerHTML = '<h1>404</h1>' } } window.onpopstate = function (e) { render(location.pathname) } render('/index') Copy the code

advantages

  • Simple to use, more beautiful
  • PushState () sets the new URL to be any URL of the same origin as the current URL, and the hash can only change the content after the #, so it can only set the same document URL as the current URL
  • A URL set by pushState() that is exactly the same as the current URL is also added to the history stack, and the content after hash# must be modified to be added to the new stack
  • PushState () can add any type of data to a record with the stateObject argument, whereas hash can only add short strings
  • PushState () sets the title property in addition for later use

disadvantages

  • The URL of the front end must be the same as the URL of the back end; otherwise, a 404 error will be reported
  • Older browsers have compatibility line issues due to the History API

Two different usage scenarios

  • As you can see from the previous section, urls in hash mode will have #, and you can use history mode when you want a more elegant URL.
  • When using history mode, be careful to add a candidate resource on the server that covers all cases: if the URL does not match any static resource, it should return the same index.html page that your app relies on.
  • You are advised to use hash mode for browsers compatible with earlier versions.
  • You can use history mode when you want to add any type of data to a record.

Reference links:

  • Front-end framework routing implementation
  • Two modes of front-end routing
  • The implementation principles of the two front-end routes (hash mode and History mode) are analyzed and distinguished