What is routing

What is a router? If one or more people want to surf the Internet at home, they need to connect to a router. The router connects to Telecom, which sells IP ports. Baidu and Douyin buy ports. When you open Tiktok on your phone, the request is dispatched by the router to Tiktok, which then sends the requested information back. Routing is about distributing requests, and routers are about distributing requests.

What is front-end routing

Front-end routing started with Ajax, Asynchronous JavaScript And XML, a technical solution used by browsers to implement Asynchronous loading.

In the early 1990s, most web pages were returned to HTML directly, and users had to refresh the page every time they updated. With the development of the network, a solution is urgently needed to improve this situation.

In 1996, Microsoft first introduced the iframe tag, which introduced the concept of asynchronous load and request elements, and then in 1998, Microsoft’s Outloook Web App team came up with the basic concept of Ajax (a precursor to XMLHttpRequest), This technology is implemented in Internet Explorer 5 via ActiveX. After Microsoft implemented this concept, other browsers like Mozilia, Safari, and Opera implemented Ajax with XMLHttpRequest. (Compatibility issues have arisen since then.) But with the release of Internet Explorer 7, Microsoft compromised and embraced the implementation of XMLHttpRequest.

With Ajax, user interaction doesn’t have to refresh the page every time, and the experience is vastly improved. But it was Google Maps that really took the technology to the next level, unleashing the true power of Ajax and unleashing the imagination of many developers beyond simple data and page interactions, paving the way for asynchronous interactions to flourish. A more advanced version of the asynchronous interactive experience is SPA, a single page application.

Single-page application is not only refresh-free in page interaction, even page jump is refresh-free, in order to achieve single-page application, so there is front-end routing. The concept of single-page applications came with MVVM. It was first proposed by Microsoft, and then they implemented Knockoutjs in the browser. But the power of the technology was not fully appreciated by developers at the time, perhaps because Knockoutjs implementations were too complex to spread widely. Again, the relay is Google. Google took MVVM and single-page apps to the next level with Angularjs, enabling front-end developers to create larger applications that became more functional and then the front-end community exploded and there were a lot of great frameworks.

Front-end routing is to assign the task of different routes corresponding to different contents or pages to the front-end, which is realized by the server returning different pages according to different URLS.

//.html <! DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <a class="link" href="/1">go to 1</a> <a class="link" href="/2">go to 2</a> <a class="link" href="/3">go to 3</a> <a class="link" href="/4">go to 4</a> <div id="app"></div> <div id="div404" style="display: none;" </div> <script SRC =" SRC /index.js"></script> </body> </ HTML >Copy the code

hashchange

Triggered when the fragment identifier in the URL changes (the part of the URL that follows the ‘#’ sign, including the ‘#’ sign)

The default route

A Default route is selected by a router when no other route exists for the destination address in an IP packet. All packets whose destination is not in the router’s routing table use the default route. This route usually goes to another router, which also handles packets: if it knows how to route the packet, it is forwarded to a known route; Otherwise, the packet is forwarded to the default route and thus to another router. Each time the route is forwarded, the distance is increased by one hop.

In the preceding example, the default route is

number = number || 1
Copy the code

404/ Guaranteed route

if(div){
    div.style.display = 'block';
}else{
    div = document.querySelector('#div404');
    div.style.display = 'block';
}
Copy the code

The routing table

const app = document.querySelector("#app"); const div1 = document.createElement("div"); div1.innerHTML = "1"; const div2 = document.createElement("div"); div2.innerHTML = "2"; const div3 = document.createElement("div"); div3.innerHTML = "3"; const div4 = document.createElement("div"); div4.innerHTML = "4"; const routeTable = { "1": div1, "2": div2, "3": div3, "4": div4 }; function route(container) { let number = window.location.hash.substr(1); number = number || 1; Let div = routeTable[number.tostring ()]; if (! div) { div = document.querySelector("#div404"); } div.style.display = "block"; Container. InnerHTML = ""; container.appendChild(div); } route(app); Window.addeventlistener ("hashchange", () => {console.log("hash changed "); route(app); });Copy the code

Embedded routines by

Div1 there are div1.1, 1.2, 1.3, etc., the specific implementation method is a bit complicated, please baidu

Hash pattern-let number = window.location.hash.substr(1);

It can be used in any situationhashDo front-end routing.

Early implementations of front-end routing were based on location.hash. The implementation principle is simple: the value of location.hash is the content after the # in the URL. For example, here’s a website whose location.hash=’#me’ :

https://www.srtian.com#me
Copy the code

In addition, hash has the following features:

In the URLhashValue is just a state on the client side, which means that when a request is made to the server side,hashParts will not be sent.

Changes to the hash value add a record to the browser’s access history. So we can switch the hash using the browser’s back and forward buttons.

We can use the HashChange event to listen for changes to the hash.

There are also two ways to trigger hSAH changes. One is to use the a tag and set the href attribute. When the user clicks the tag, the URL will change and the hashchange event will be triggered:

<a href="#srtian">srtian</a>
Copy the code

Alternatively, you can assign to loaction.hash directly in JavaScript to change the URL and trigger the hashchange event:

location.hash="#srtian"
Copy the code

To clarify, if we were to implement a route using a hash pattern, the flow would look like this.

Cons -SEO is not friendly

Main cause: The server cannot receive hash

Google has SEO for Hash, #! (hashbang), if found after #! “, then Google will think it’s a different page, but it’s still not as good as old SEO and basically useless.

The history mode-let number = window.location.pathname;

The history mode can be used when the back end renders all the front-end routes to the same page. Vue-router defaults to hash mode — the hash of a URL is used to simulate a full URL so that the page does not reload when the URL changes.

If you don’t want ugly hashes, you can use the history mode of the route, which takes full advantage of the history.pushState API to do URL jumps without reloading the page.

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
Copy the code

When you use history mode, the URL looks like a normal URL, for example

http://yoursite.com/user/id
Copy the code

Also good!

However, this mode to play well, but also need background configuration support. Because our application is a single page of the client application, if there is no correct configuration, the background when the user directly in the browser to http://oursite.com/user/id will return to 404, it’s not good-looking.

So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app relies on.

Disadvantages – Internet Explorer 8 is not supported

The memory model-let number = window.localStorage.getItem("xxx");

The previous two patterns are both derived from different urls. The memory mode stores the path to a location that the user cannot see, such as localStorage. And the search path URL is unchanged, by fetching different paths from the repository to achieve routing.

Memory mode is suitable for non-browser routes, such as routes in apps, which are not web pages and have no path. So you have to use memory mode. React Native, for example, has no path.

conclusion

Hash and history both store paths in urls. Memory doesn’t use urls. The disadvantage of memory is that there is no URL, because the path is not put in the URL, but stored in the local repository, so this is a stand-alone route, I share this URL, because you have no path information, so keep the original route.

Vue – the router source code