The other

Front-end routing starts with Ajax, Asynchronous JavaScript And XML, a technical solution used by browsers to implement Asynchronous loading. To say famously: there is no front-end routing in the world, the demand for more people, also appeared the term front-end routing.

What is front-end routing

The concept of routing is the mapping between urls and processing functions on the server. Front-end routing is reflected in single-page applications and describes the mapping between URL and UI page. In other words, UI updates are caused by URL changes (no page refresh is required).

How to implement

  1. How can I change the URL without causing a page refresh?
  2. How do I detect URL changes?

Implementation method

Hash implementation

  • Hash implementation: The hash is the part after the URL. If you change the HASH in the URL, the page will not be refreshed
  • Hashchange (native JS)
<body> <ul> <li><a href="#/home">home</a></li> <li><a href="#/about">about</a></li> </ul> <div id="routerView"></div> <script> var routerView = document.getElementById('routerView') window.addEventListener('DOMContentLoaded',onHashChange) Window.addeventlistener ('hashchange', onHashChange) function onHashChange() {console.log(location); window.adDeventListener ('hashchange', onHashChange) function onHashChange() {console.log(location); switch (location.hash) { case '#/home': routerView.innerHTML = 'Home Page' break; case '#/about': routerView.innerHTML = 'About Page' break; default: return } } </script> </body>Copy the code

The history to achieve

  • History implementation: an object provided by HTML that provides pushState and replaceState methods, both of which can change the URL without causing a page refresh
  • PopState can listen for urls changed by pushState and replaceState
  • Calls to pushState and replaceState and click events for the A tag can be intercepted
<body> <ul> <li><a class="link1" href="/home">home</a></li> <li><a class="link2" href="/about">about</a></li> </ul> <div Id ="routerView"></div> <script> // if pushState or replaceState is used, AddEventListener (' popState ',onLoad) function onPopState() {// console.log(location.pathname); switch (location.pathname) { case '/home': routerView.innerHTML = '<h2>HOME page</h2>' break; case '/about': routerView.innerHTML = '<h2>ABOUT page</h2>' break; default: break; }} function onLoad() {var routerView = document.getelementById ('routerView') onPopState(  document.querySelectorAll('ul li a') // console.log(linkList); Linklist.foreach (el => {el.adDeventListener ('click', function(e) {e.preventDefault(); History. pushState(null, ", el.getAttribute('href')) // OnPopState ()})} window.addeventListener ('DOMContentLoaded', onLoad) </script> </body>Copy the code

conclusion

The above two methods are the implementation of front-end routing, in the early learning of these conceptual understanding is quite important, if where said not good welcome big boss correction, beg praise beg support!