Front-end Routing Implementation Method

Source: Internet
Author: User
Keywords routing routing meaning routing meaning in networking
First, what is front-end routing

In the process of web development, the use of routing is essential. The routing here does not refer to routers in our daily lives, but the implementation principle is basically the same. It represents the insinuation relationship between a URL and the corresponding processing program. After visiting the url, the route will parse the path in the url, then look up the corresponding preset function according to the mapping relationship in the mapping table, and return the result to the user to complete an operation.

Front-end routing is different from traditional routing in that it does not require a server to parse, but is implemented through a hash function or history API provided by H5. During development, routing is used to set the access path and map the path to the corresponding component. When the user accesses the corresponding path, the routing implements switching between different components according to the mapping relationship, and the whole process is on the same page It does not involve jumps between pages, which is what we often call single-page applications.

Second, the advantages of front-end routing

1. The page refresh speed is fast. Since the back-end routing requests a new path, it will re-send the request to the server, and then re-render the page according to the server's corresponding results. This process will be affected by network delays, while the front-end routing omits the entire request process and only completes the part. Switching between components, so the page refresh speed will be relatively fast, and the user experience is relatively good.

2. Strong reusability. Using front-end routing, the layout, css, and js in the code can be shared to reduce repeated loading and improve program performance.

3. The page status can be recorded. For single-page applications that do not use front-end routing and only partially switch the page through ajax, because the url always remains the same, the state of the page cannot be recorded, and the front-end routing solves this problem well. For example, using the front-end routing URL: http://music.taihe.com/fe/a This link will directly trigger the /a event after opening it.

Third, the realization method of front-end routing

There are currently two main ways to implement front-end routing, location.hash and window.history.

1. Realize front-end routing through location.hash

The hash is the part after # in a url, also called the anchor part of the url. The anchor part will be automatically ignored on the server side, but it can be obtained through loaction.hash in the browser. The front-end routing through the hash method mainly uses the onhashchange event, which can monitor the change of the hash value in the url in real time, thereby performing some DOM switching operations according to the change of the hash value.

The syntax of onhashchange is as follows:

In HTML:

<element onhashchange="myScript">

In Javascipt:

Object.onhashchange=function(){myScript};

In Javascript, use the addEventListener() method:

Object.addEventListener("hashchange", myScript);

The onhashchange event has the following trigger conditions:

A) Change the URL address and add or change its hash value at the end;

B) Change the value of location.href or location.hash;

C) Click on the link with an anchor point;

D) Forward and backward browsers may cause changes in the hash, provided that the hash values in the two web addresses are different.

Use Hash to implement front-end routing:

Design idea: When the hash value of the url of the browser address bar changes, the onhashchange event will be triggered. At this time, the hash value of the current browser url can be obtained through window.location.hash. Note that the hash value at this time is with There are #, so its value needs to be processed accordingly, # is removed, and if the current URL does not contain a hash value, it will be treated as the root directory. After that, the URL and the corresponding component function are mapped, and different callback functions are executed according to different hash values, that is, the corresponding component is loaded.


2. Realize front-end routing through window.history and popstate

The browser window will provide the user with a history object, which is used to save the history of the user's operation of the page. Our forward and backward operations when browsing the web are all implemented based on this object. The history.pushState() and history.replaceState() in the history object are mainly used in the implementation of the front-end routing.

History.replaceState(dataObj,title,url); history.replaceState(dataObj,title,url);

History.pushState(dataObj,title,url); history.pushState(dataObj,title,url);

The pushState() and replaceState() methods are very similar. Both accept three parameters, state, title, and url. Among them, state is used to store the related information of the history entity to be inserted. It is a parameter in json format; title is the title of the passed in history entity. It should be noted that firefox will now automatically ignore this parameter; url is used to pass new The relative path of the history entity. If its value is null, it means that the current history entity to be inserted is consistent with the previous entity and has not changed. The only difference between the replaceState() method and the pushState() method is that the replaceState() method will overwrite the latest history entity instead of adding it directly. In this case, for example, the login page does not need to be recorded in the history. Very useful at times.

It should be noted here that the two methods provided by history will not initiate the refresh of the browser page, but the content of the history object including the address bar will change, and the corresponding response will be made when the history events such as forward and backward are set out. In addition, the url passed in as a parameter will also be restricted by the same-origin policy, and an error will be reported if cross-domain conditions occur.

Popstate is an official event, which is triggered when the record in history changes.

Use history to realize front-end routing:

Design idea: When you want to jump to the specified url, fill the target url into the history and address bar through pushState() or replaceState(). At this time, because the above two methods will not actively refresh the page, so The page still stays on the current page, but the url address has changed. After responding to the popstate event, the corresponding callback function is executed to switch between front-end components.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.