This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging
directory
Why do we use
Front-end routing implementation
1. The hash pattern
2. The history mode
Why do we use
A partial AJAX refresh causes the request to be completed without any change to the browser’s URL, thus ruining the user experience. At the same time, the content of the browsing page cannot be presented again when the user visits the URL next time. Using routing can solve this problem well.
Single-page applications use JavaScript to dynamically transform web content, avoiding page reloading. Routing allows the browser address to change and the web content to change, and the combination of the two gives us a good single-page Web application experience.
Front-end routing implementation
In a single-page Web page, the web page will not be overloaded if the browser address changes simply. For example, the web page will not change if the hash url changes simply. Therefore, our route is mainly through listening to events and using JS to dynamically change the content of the web page.
Hash mode: Monitor the hash value of the browser address and perform the corresponding JS to switch the web page.
History mode: Use history API to realize URL address change, web content change; The most obvious difference is that hash adds a # to the browser address, while History allows you to customize the address.
1. The hash pattern
Using the window.location.hash attribute and the onHashChange event of the window, you can monitor the hash value change of the browser address and perform the corresponding JS switch to the web page. Here are a few points that must be understood in the process of use:
-
The hash is the hash and the following characters in the address, also known as the hash value. The hash, also known as the anchor point, is itself used to redirect the page. 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 will not reload the page;
-
Listen for the window hashChange event. When the hash value changes, you can use location.hash to get and set the hash value;
-
Changes in the location.hash value are directly reflected in the browser address bar.
There are several ways to trigger a HashChange event:
-
The change of the hash value of the browser address bar (including the forward and backward of the browser) triggers the change of the window.location.hash value, which triggers the onHashChange event.
-
When the URL in the browser address bar contains a hash such as http://www.baidu.com/#home, press enter and the browser sends a request to the server for http://www.baidu.com/. When the request is complete, set the hash value to #home. This in turn triggers the OnHashChange event;
-
When you change only the hash part of the URL in the browser address bar, you press Enter, and the browser doesn’t send any requests to the server, all you do is set the hash value, the new hash value, and trigger the onHashChange event;
// Set the HASH of the URL to add '# ABC 'to the current URL.
window.location.hash='abc';
let hash = window.location.hash //'#abc'
window.addEventListener('hashchange'.function(){
// Listen for hash changes, which are triggered by clicking the browser forward or backward
})
Copy the code
2. 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 a change occurs, only the path of the page is changed, and the page is not refreshed. The History object holds the urls of all the pages visited by the current window. Using history.length, you can get the total number of urls visited in the current window. For security reasons, browsers do not allow scripts to read these addresses, but do allow navigation between them. The “forward” and “back” buttons on the browser toolbar operate on the History object.
attribute
The History object has two main properties.
- History.length: Number of urls visited in the current window (including the current page)
- History.state: the state value at the top of the History stack (more on this below)
// How many pages have been visited in the current window
history.length / / 1
// The current state of the History object
// This is usually undefined, that is, not set
history.state // undefined
Copy the code
methods
The three methods of history.back (), history.forward (), and history.go () are used to move through History.
History.back()
: Moving to a previous url is equivalent to clicking the browser’s back button. This method has no effect on the first url visited.History.forward()
: Moving to the next url is equivalent to clicking the browser’s forward button. This method has no effect on the last url visited.History.go()
: Takes an integer as a parameter and moves to the specified url 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 is equivalent to 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
Copy the code
Note: When you move to a previously visited page, the page is usually loaded from the browser cache, rather than asking the server to send a new page.
History.pushState()
This method is used to add a record to the history. The pushState() method does not trigger a page refresh, but causes the History object to change and the address bar to change.
PushState (object, title, URL)
This method takes three arguments, in order:
- Object: is an object whose contents can be passed to the new page using the pushState method. If the object is not needed, null can be entered.
- Few browsers support this parameter. It is safer to pass an empty string.
- Url: The new url, which must be in the same field as the current page. If not specified, it is the current path. If a cross-domain address is set, an error is reported.
var data = { foo: 'bar' };
history.pushState(data, ' '.'2.html');
console.log(history.state) // {foo: "bar"}
Copy the code
Note: If the pushState URL parameter sets a new anchor value (hash), the HashChange event is not triggered. Conversely, if the URL’s anchor value changes, a browsing History is created in the History object.
If the pushState() method sets a cross-domain url, an error will be reported.
/ / an error
// The current url is http://example.com
history.pushState(null.' '.'https://twitter.com/hello');
Copy the code
In the above code, pushState tries to insert a cross-domain url, causing an error. This is designed to prevent malicious code from making users think they are on another site, as this method does not cause the page to jump.
The history.replacestate () method is used to modify the current record of the History object and is used 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({page: 2}, ' '.'? page=2');
/ / URL displayed as http://example.com/example.html?page=2
history.replaceState({page: 3}, ' '.'? page=3');
/ / URL displayed as http://example.com/example.html?page=3
history.back()
/ / URL displayed as http://example.com/example.html?page=1
history.back()
/ / URL displayed as http://example.com/example.html
history.go(2)
/ / URL displayed as http://example.com/example.html?page=3
Copy the code
Popstate event
The POPState event is triggered every time the History object changes.
Note:
Just calling the pushState() or replaceState() method does not trigger the event; 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 the browsing history causes different documents to be loaded. The browser does not emit the PopState event when the page is first loaded. When used, you can specify a callback function for popState events. The argument to the callback function is an event event object whose state property points to the current state object.
window.addEventListener('popstate'.function(e) {
//e.state is equivalent to history.state
console.log('state: ' + JSON.stringify(e.state));
console.log(history.state);
});
Copy the code
Click to see how you can use history.pushState to switch between pages.
The fatal flaw of history is that when the browser is forced to refresh after changing the address of the page (if the back end is not prepared), an error will be reported because the refresh will request the server with the current address. If the server does not respond, a 404 page will appear.
If this article helped you, remember to like 👍 collection and follow oh 😊, hope to like a lot more…
If there are any mistakes in this post, feel free to correct them in the comments section