Refer to some blogs to sort out for their own review ~ because their interview has been asked

Why route

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.

The way front-end routing is implemented

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.

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 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 with the request to the server, so change the hash, 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, are triggeredwindow.location.hashValue changes, thereby triggeringonhashchangeEvents.
  • When a URL in the browser address bar contains a hash such ashttp://www.baidu.com/#home“, then press Enter and the browser sendshttp://www.baidu.com/Request to the server and set the hash value to#homeAnd triggeronhashchangeEvents.
  • When only changing the browser address barURLWhen you press Enter, the browser will not send any requests to the server. All that happens is that the hash value is set and the newly changed hash value is triggeredonhashchangeEvents.
  • The HTML < a >Attributes of tagshrefCan be set to an element of the pageIDSuch as#topWhen clicking the link, the page is redirected to theidElement is set automatically by the browserwindow.location.hashProperty, the hash value in the address bar also changes, and firesonhashchangeEvents.
// Set the URL hash to add '# ABC 'after the current URL.
window.location.hash='abc';
let hash = window.location.hash //'#abc'

window.addEventListener('hashchange'.function(){
	// Listen for hash changes, triggered by clicking the browser's forward and back
})
Copy the code

The history mode

  • 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: The state value at the top of the History stack (see more below)
// How many pages are visited by the current window
history.length / / 1

// History Specifies the current state of the object
// Undefined, i.e. not set
history.state // undefined
Copy the code

methods

Back (), history.forward (), history.go ()

  • 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
Copy the code

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.

history.pushState(object, title, url)

  • 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"}
Copy the code

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.

/ / an error
// The current website 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({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 emitted every time the History object changes.

  • 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.