Why use routing
Today’s web applications are increasingly using AJAX asynchronous requests to complete seamless page refreshes, resulting in the browser’S URL completing the request without any change, thus changing the user’s browsing experience. At the same time, the contents of the browsing page will not be re-presented when the user accesses the URL next time. Routing can solve this problem well.
Single page application uses JavaScript to dynamically transform web content, avoiding page reloading. Routing allows the browser address to change, and the content of the page to follow, which combined to provide a well-experienced single-page Web application.
Implementation of front-end routing
Routing needs to implement the following functions:
-
Switch pages when the browser address changes.
-
Click the “Back” and “Forward” buttons of the browser, and the webpage content will follow the changes;
-
Refresh the browser and load the current route on the web page.
In single-page Web pages, simple browser address changes will not overload the page, such as simple hash URL changes will not change the page, so our routing is mainly by listening for events and using JS to dynamically change the content of the page. There are two ways to achieve this:
- Hash mode: Monitors the hash value change of the browser address and executes the corresponding JS to switch the web page.
- History mode: use the history API to change the URL address and change the web content;
The most obvious difference is that hash adds a # to the browser address, while history allows you to customize the address.
Hash pattern
Using the window.location.hash attribute and the onHashchange event of the window, you can monitor the hash value of the browser address and execute the corresponding JS to switch the web page. Here are some key points you must understand in the process of using:
-
Hash refers to the # and the character that follows the address, also known as the hash value. Hashes, also known as anchors, are themselves used to navigate pages. Such as http://localhost/index.html#abc, the # of ABC is to hash;
-
The hash value is not sent to the server with the request, so changing the hash does not reload the page;
-
Listen for the window hashchange event. When the hash value changes, you can set the hash value via location.hash.
-
Changes to the location.hash value are directly reflected in the browser address bar;
The hashchange event can be triggered in several ways:
-
Changes in the hash value of the browser address bar (including browser forward and backward) trigger changes in window.location.hash, which triggers the onHashChange event.
-
When the URL in the browser address bar contains a hash such as www.baidu.com/#home, press to enter…
-
When you change only the hash part of the URL in the browser’s address bar and press Enter, the browser doesn’t send any requests to the server. All that happens is that you set the hash value, the newly changed hash value, and the onHashChange event is triggered.
-
In HTML, the attribute href of a tag can be set to the page element ID, such as # TOP. When clicking this link, the page will jump to the area where the ID element is located. Meanwhile, the browser will automatically set the window.location.hash attribute, and the hash value in the address bar will also change. And triggers the onHashchange event;
// To hash the URL, add ‘# ABC ‘window.location.hash=’ ABC’ after the current URL; let hash = window.location.hash //’#abc’
Window.addeventlistener (‘hashchange’,function(){// Listen for hash changes, triggered by clicking browser forward or back})
The history mode
An overview of the
- The window.history property points to the History object, which represents the browsing history of the current window. When changes are made, only the path of the page is changed, not the page is refreshed.
- The History object holds the url of all pages visited by the current window.
- History. length shows how many urls the current window has visited.
- For security reasons, the browser does not allow the script to read these addresses, but does allow navigation between them.
- The “forward” and “back” buttons on the browser toolbar actually operate on the History object.
attribute
The History object has two main properties.
-
History.length
: Number of urls visited by the current window (including the current page) History.state
: state value at the top of the History stack (see below)
History. length // 1 // the current state of the history object // is usually undefined, i.e. history.state is not set // undefinedCopy the code
methods
Back (), history.forward (), history.go ()
These three methods are used to move through history.
-
History.back() : Move to the previous url, equivalent to hitting the browser’s back button. This method has no effect on the first url visited.
-
History.forward() : Moves to the next url, equivalent to clicking the browser’s forward button. This method has no effect on the last url visited.
-
History.go() : takes an integer as an argument and moves to the url specified by the argument, based on the current url. If the parameter exceeds the actual url range, the method has no effect. If no parameter is specified, the default parameter is 0, which means refreshing the current page.
history.back(); history.forward(); history.go(1); // equivalent to history.forward() history.go(-1); // equivalent to history.back() history.go(0); // Refresh the current page
Note: When you move to a previously visited page, the page is usually loaded from the browser cache, rather than re-asking the server to send a new page.
History.pushState()
This method is used to add a record to history. The pushState() method does not trigger a page refresh, but only causes the History object to change and the address bar to change.
Syntax: history.pushState(object, title, URL)
The method accepts three parameters, in order:
-
Object: is an object whose contents can be passed to a new page using the pushState method. If this object is not needed, null can be used here.
-
Title: Index question. Few browsers support this parameter. It is safer to pass an empty string.
-
Url: The new url must be in the same domain as the current page. If not specified, the current path is used. If a cross-domain URL is set, an error is reported.
var data = { foo: ‘bar’ }; history.pushState(data, ”, ‘2.html’); console.log(history.state) // {foo: “bar”}
Note: If the URL parameter to pushState sets a new anchor value (that is, a hash), the Hashchange event is not triggered. Conversely, if the anchor value of the URL changes, a browsing record is created in the History object.
If the pushState() method sets a cross-domain URL, an error is reported.
The correct / / / / the current site is http://example.com history. PushState (null, "', 'https://twitter.com/hello');Copy the code
In the code above, pushState attempts to insert a cross-domain URL, causing an error. This is designed to prevent malicious code from making users think they are on a different site, since it does not lead to a page jump.
History.replaceState()
This method is used to modify the current record of the History object in the same way as the pushState() method.
Assume the current web page is example.com/example.html.
history.pushState({page: 1}, '', '? Page = 1 ') / / URL displayed as http://example.com/example.html?page=1 history. PushState ({2} page: "', '? Page = 2 '); / / URL displayed as http://example.com/example.html?page=2 history. ReplaceState ({3} page: "', '? Page = 3); / / URL displayed as http://example.com/example.html?page=3 history. The back () / / URL is http://example.com/example.html?page=1 History. The back () / / URL to http://example.com/example.html history. The go (2) / / URL shown as http://example.com/example.html?page=3Copy the code
Popstate event
The PopState event is emitted every time the History object changes.
Note:
-
This event is not triggered by simply calling the pushState() or replaceState() methods;
-
This is triggered only when the user clicks the browser’s back and forward buttons, or calls the history.back (), history.forward (), and history.go () methods using JavaScript.
-
In addition, this event is only for the same document and will not be triggered if a switch in browsing history results in a different document being loaded.
-
The browser does not trigger the PopState event when the page first loads.
When used, you can specify a callback function for a popState event that takes an event object whose state property points to the current state object.
Window.addeventlistener (' popState ', function(e) {//e.state equals history.state console.log('state: ' + JSON.stringify(e.state)); console.log(history.state); });Copy the code
The fatal drawback of History is that when the browser is forced to refresh after a change in page address (if the back end is not prepared), an error is reported because the refresh request is made to the server with the current address, and if there is no response from the server, a 404 page will appear.