HTML5 History mode and html5history Mode
I recently saw the implementation of vue-router's HTML5 History mode routing, And then I studied HTML5's History by the way. Here are some of my own understandings, by the way, use jquery to write a vrohtml5 similar to the HTML5 History mode in vue-router, so that you can be familiar with it.
I. history. pushState
history.pushState(state, title, url
);
The first and second parameters can be null, mainly the third parameter, indicating the address of the new historical record. the browser will not load this URL after calling the pushState () method, the new URL is not necessarily an absolute address. If it is relative, it must beRelative to the current URL
Ii. history. replaceState
history.replaceState(state, title, url
);
window.history.replaceState
Andwindow.history.pushState
Similarly, the difference is thatreplaceState
Not inwindow.history
Add a historical record point in, the effect is similarwindow.location.replace(url)
.
III,window.onpopstate
To listen for url changes
Window. addEventListener ("popstate", function () {var currentState = history. state;/** program to be executed after the event is triggered */});
// Or
window.onpopstate
= Function (){}
Javascript script executionwindow.history.pushState
Andwindow.history.replaceState
Not triggeredonpopstate
Event. It is triggered when you click forward or backward in the browser.
The first time Google and Firefox opened their pages, the response was different.onpopstate
But Firefox does not.
4. The following is an example of the HTML5 mode similar to vue-router, which is purely a deep understanding and rough to write.
<! DOCTYPE html>
By the way, I pasted a server code in node. js. For testing, I wrote a simple
Var fs = require ('fs') var path = require ('path') var express = require ('express ') var app = express (); app. use (express. static ('. /public '); var router = express. router (); router. get ('/page', function (req, res) {var page = req. query. page try {var text = fs. readFileSync ('. /data '+ page + '. json '); res. json (text. toString ()} catch (err) {res. send ('haha! Silly, not pulling! ')}) App. use (router) app. listen (3000)
Note:History. pushState ({pageIndex: 1}, "", "http: // 127.0.0.1: 3000/lmw/" + query) The third parameter writes the complete absolute path, if you write a relative path like "/lmw/" + query, it will be appended to the url infinitely as the query is worth adding, because the relative path must be relative to the current URL
The server stores data0.json, data1.json, and data2.json to simulate the database to fetch data. The server obtains the index value (0/1/2) from the front end to read the data *. json file and then sends it to the front end.