This is the 13th day of my participation in Gwen Challenge

Since the project was going live soon, the analysis of user behavior trajectory was not taken into account. Recently just prepare to update the performance monitoring platform of the front end, just do it, and analyze the practice of the front end routing. I remember two years ago when I was doing Android development, the OEM version of the customer asked Google analytics to do page flow analysis and error monitoring. At that time, it was buried point, and the front-end page flow had better be done through the route, so that the buried point position is better to control the point.

Overview of back-end routes

The idea of routing first came from the back end. You’ve often seen this in the past when developing pages with template engines

http://www.xxx.com/login
Copy the code

The general process can be viewed as follows:

  • The browser makes a request
  • The server listens for a request on port 80 (or 443) and parses the URL path
  • Return information (HTML strings, JSON data, images, etc.) based on the routing configuration of the server
  • Does the browser decide how to parse data based on the packet’s Content-Type

To put it simply, routing is a way to interact with back-end servers. It is one of the functions of routing to request different resources and pages through different paths.

Single page switching

When a user switches addresses, it is a local update without refreshing. There is no way to trigger beforeunload. So the single-page routing plugin must use the window’s pushState and replaceState methods. While users of a non-single page application can use window. beforeUnload events that are triggered when the page leaves.

Several methods of the history object

History provides two methods to modify the user’s browsing history without refreshing. PushSate and replaceState differ from pushState, which adds an access record to the end of the user’s page. ReplaceState replaces the current access record directly.

history.pushState

The history.pushState method takes three arguments, in order:

  • State: a state object associated with the specified url that is passed in a callback function when the POPState event is triggered. If this object is not needed, null can be used here.
  • Title: The title of the new page, but all browsers currently ignore this value, so null can be filled here.
  • Url: The new url must be in the same domain as the current page. The browser’s address bar will display the url. Assuming the current url is example.com/1.html, we use the pushState method to add a new record to the history object.

When you add this new record, the browser’s address bar immediately shows example.com/2.html, but it doesn’t jump to 2.html or even check for the existence of 2.html, it just becomes the latest record in your browsing history. At this point, you enter a new address in the address bar (e.g. Google.com) and click the back button. The page URL will display 2.html. You click the back button again and the URL will display 1.html.

In summary, pushState does not trigger a page refresh, but only causes the history object to change and the address bar to respond. If the URL argument to pushState sets a new anchor value (that is, a hash), the Hashchange event is not triggered. If a cross-domain URL is set, an error is reported.

/ / an error
history.pushState(null.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 another site.

history.replaceState

The history.replaceState method takes exactly the same parameters as the pushState method, except that it modifs the current page in the browsing history, assuming that the current page is example.com/example.html.

history.pushState({page: 1}, 'title 1'.'? page=1');
history.pushState({page: 2}, 'title 2'.'? page=2');
history.replaceState({page: 3}, 'title 3'.'? 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

Back, history.forward, history.go, length

In HTML4, Histroy objects had the following attribute methods:

  • 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, for example, go(1) equals forward() and go(-1) equals back(). 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.go (0) is equivalent to refreshing the current page.

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.

Popstate event

The PopState event is triggered every time the browsing history (that is, the history object) of the same document changes.

Note that calling the pushState() or replaceState() method alone does not trigger this event, only if the user clicks the browser back button and forward button, Or when the history.back (), history.forward (), and history.go () methods are called 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.

When used, you can specify a callback function for popState events.

window.onpopstate = function (event) {
  console.log('location: ' + document.location);
  console.log('state: ' + JSON.stringify(event.state));
};

/ / or
window.addEventListener('popstate'.function(event) {
  console.log('location: ' + document.location);
  console.log('state: ' + JSON.stringify(event.state));
});
Copy the code

The argument to the callback function is an Event event object whose state property points to the state object provided by the pushState and replaceState methods for the current URL (that is, the first argument to both methods). The event.state in the above code is the state object that is bound to the current URL using the pushState and replaceState methods.

The state object can also be read directly from the history object.

var currentState = history.state;
Copy the code

Note that the browser does not trigger the PopState event when the page first loads.

Simulate single-page routing

When doing management system, we usually place a fixed navigation sidebar on the left side of the page, and put the corresponding content main on the right side of the page. When you click on navigation, you just want the content to be updated, and if you refresh the entire page and redraw the bottom of the navigation and general header, it’s a waste of resources and a bad experience. At this point, we can use what we learned today by using HTML5’s pushState and replaceState methods,

  • First bind the click event. PreventDefault when the user clicks on a link, prevent the default behavior with the preventDefault function and read the link’s address (if jQuery is available)(this).attr('href'))PushState pushes the address into the browser history, using Ajax pull (you can use jquery’s get() method) to pull the actual content from the address and replace the current web page’s content.

To handle users moving forward and backward, we listen for popState events. When the user clicks the forward or back buttons, the browser address is automatically converted to the corresponding address and a POPState event occurs. In the event handler function, we grab the corresponding content according to the current address, and then use AJAX to pull the real content of the address, rendering, and then. Finally, the entire process does not change the page title, which can be changed by assigning document.title directly.

Single page application user access trace buried points

Those of you who have developed a single page application must be quite aware that the route switching of a single page application is unconscious. Instead of making HTTP requests again to obtain the page, it is realized by changing the page rendering view. So his implementation principle must also be through the native pushState or replaceState implementation. To record the user’s jump information, we simply intercept pushState and replaceState and execute our method before performing the silent behavior to collect the user’s jump information

// Change the idea: Copy the window default replaceState function, override history.replaceState, insert our collection behavior in the method, and call the window default replaceState method at the end of the override replaceState method

collect = {}

collect.onPushStateCallback : function(){}  // Custom collection method

(function(history){
    var replaceState = history.replaceState;   // Store the native replaceState
    history.replaceState = function(state, param) {     / / replaceState
       var url = arguments[2];
       if (typeof collect.onPushStateCallback == "function") {
             collect.onPushStateCallback({state: state, param: param, url: url});   // Custom collection behavior method
       }
       return replaceState.apply(history, arguments);    // Call the native replaceState}; }) (window.history);

Copy the code

conclusion

This article introduces the application of pushState method and replaceState in many aspects

The above! Last rule, post my blog, welcome to follow

Please pay attention to the official number: Full stack flying Squadron