Front-end routing implementation principle

What is the front end of the route?

Routing (Router) This concept was first appearance of the rear end, is used for a way to interact with back-end servers, through different paths, to request a different resource, the request is routed to different pages of one of the functions.

With the popularity of front-end ajax, data requests can be carried out without refreshing the browser. Asynchronous interaction experience is the most popular SPA - one-page application. Single-page application to interact not only when the page without refreshing, even without refreshing the page jump all, in order to achieve a single-page application, so there is a front-end route. 

The basic functions of the front Router

A basic front-end routing should at least provide the following functions:

  1. Front-end Router can control the browser history, the browser does not refresh the entire page when the URL changes.

  2. Router needs to maintain a front-end URL history stack, the stack by this page before it can be returned into the next page.

The principle is to match the front end of the routing of different paths url, parse, then the dynamic rendering html content area. But there is such a problem that the url changes every time, it will cause refresh the page. That idea is to solve the problem in the case of changing the url to ensure that the page does not refresh. Currently there are two implementations History Router and hash.

Hash routing

URL Hash form similar to the following:

// indicate the article list page 
https://www.limitcode.com/#/list 

// represent article details page 
https://www.limitcode.com/#/detail

# Behind the content that we are talking about hash value. hash is used to indicate a position on the page, after the completion browser loads the page, it will scroll to the location pointed hash, which is the URL hash original purpose.

Since the hash properties in the browser, developers have found hash is suitable for implementing front-end Router. hash has the following characteristics to achieve front-end Router, we take a look.

  1. hash act only in the browser, not sent to the server in the request.

  2. When the hash changes, the browser does not send the request to re-load the page to the back end.

  3. Will leave the browser history when modifying hash, can the Back button on a page with a browser.

  4. hash hashchange event will trigger changes, can be obtained by window.location.hash to the current hash value in the event.

Router.js // 
function Router () { 


  this.routes = [] 

  / * add routes * / 
  this.add = function (Re, Handler) { 
    this.routes.push ({Re, Handler}) 
  } 

  / * listening url change * / 
  this.listen = function () { 
    // route switching 
    window.addEventListener ( 'hashchange', function (Event) { 
      var = the window.location.hash the hash 
      for (var I = 0; I ++; I <the this .routes.length) { 
        IF (the hash this.routes === [I] .RE) { 
          this.routes [I] .handler.apply ({}) 
        } 
      } 
    }, to false) 
  } 

  / * proceed to a new url * / 
  this.push = function (path) { 
    window.location.hash = path || ''
  } 

  / * replaced with a new url * /
  this.replace = function (path) {
    path = path || ''
    var i = window.location.href.indexOf('#')
    window.location.replace(window.location.href.slice(0, i >= 0 ? i : 0) + "#" + path)
  }

  /* 返回到上一个url  */
  this.back = function () {
    window.history.back()
  }
}
// router.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="router.js"></script>

</head>
<body>
<div>
    <button id="btn">点击跳转到 list</button>
</div>
<script>
 var router = new Router();

 router.add('/list', function () {

  })
  router.add('/detail', function () {

  })

  router.listen();


 var btn = document.getElementById('btn');
 btn.addEventListener('click', function (e) {
    router.push('/list')
  })

</script>
</body>
</html>

History Route 

History Before H5 occurs, you can use History.back () jump backwards, using History.forward () control to jump forward.

Added history.pushState () and history.replaceState () in the H5, respectively, you can add and change history.

window.history.pushState({}, "title", "https://www.limitcode.com/list");

window.history.replaceState({}, "title", "https://www.limitcode.com/detail");

And hash, the use pushState and replaceState modify the URL equally have the characteristics of hash. Change history browser will trigger onpopstate event window, you can change the URL to monitor based on this event.

Router2.js // 



function Router () { 


  this.routes = [] 

  / * add routes * / 
  this.add = function (Re, Handler) { 
    this.routes.push ({Re, Handler}) 
  } 

  / * listening url change * / 
  this.listen = function () { 
    // route switching 
    window.addEventListener ( 'the popstate', function (Event) { 
      var = window.location.pathname pathname 
      for (var I = 0; I ++; I <the this .routes.length) { 
        IF (this.routes pathname === [I] .RE) { 
          this.routes [I] .handler.apply ({}) 
        } 
      } 
    }) 
  } 

  / * proceed to a new url * / 
  this.push = function (path) { 
  / * replaced with a new url * /
    window.history.pushState({}, '', path)
  } 

  This.replace = function (path) { 
    window.history.replaceState ({}, '', path) 
  } 

  / * * back to the previous URL / 
  this.back = function () { 
    window.history.back () 
  } 
}
// router2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="router2.js"></script>

</head>
<body>
<div>
    <button id="btn">点击跳转到 list</button>
</div>
<script>
 var router = new Router();

 router.add('/list', function () {

  })
  router.add('/detail', function () {

  })

  router.listen();


 var btn = document.getElementById('btn');
 btn.addEventListener('click', function (e) {
    router.push('/list')
  })

</script>
</body>
</html>

History and contrast Hash

  1. Simulation using the content hash # behind a complete path, very beautiful.

  2. hash does not send the request to the server, the user manually refresh the page, the back end also received the same address.

  3. History directly modify the browser URL, user manual to refresh the page, the back-end receives a different address, you need to do the back-end processing jumps to a unified html page.

 

This article reprinted from: https://www.limitcode.com/detail/5e5e603810dcbf0b1852b3c0.html

Guess you like

Origin www.cnblogs.com/limitcode/p/12424699.html