Introduce the hash

https://xxx/xxx/xxx.html#look

# represents a location in a web page. When the browser reads the URL, it automatically scrolls the position of the identifier after # into the viewable area.

You can specify an identifier for a web page location in the following way.

  • Using anchor points,<a name="look"></a>
  • Using the ID attribute,<p id="look">.

#Some characteristics of

  1. # is used to direct browser actions and is completely useless on the server side. Therefore, # is not included in the HTTP request.
  2. Change **#**, the page will not refresh
  3. Changing **#** alters the browser’s access history

read#

Hash reads the # value from window.location.hash, and can also set the # value from window.location.hash to generate a history.

Implements front-end routing using Hash

The essence of routing is that when the URL of a page changes, the page display results can be changed according to the URL change, but the page is not refreshed. Based on the hash features, front-end routing can be implemented using hash.

Hashchange is a listener, and we can use the listener event callback to show and hide different UI display functions for front-end routing.

Onhashchange event

This is a new HTML 5 event that is triggered when the # value changes. Internet Explorer 8+, Firefox 3.6+, Chrome 5+, and Safari 4.0+ support this event.

It can be used in three ways:

  • window.onhashchange = function(event){… };
  • <div onhashchange="func();" >
  • Window. The addEventListener (” hashchange “, function (event) {… }, false);

For browsers that do not support onHashchange, you can use setInterval to monitor changes to location.hash.

Pros and cons of Hash

Advantages:

  1. Only the front end needs to configure the routing table, but the back end does not need to participate
  2. Good compatibility, browser can support
  3. Changes in the hash value do not send requests to the back end, but belong to front-end routes

Disadvantages:

  1. The hash value must be preceded by a #, which is not in accordance with the URL specification and is not beautiful
  2. The server cannot accurately track the front-end routing information
  3. Conflicts with the anchor location element