1. Routing table

const app = document.querySelector("#app");
const div1 = document.createElement("div");
div1.innerHTML = "1"; 
const div2 = document.createElement("div"); 
div2.innerHTML = "2"; 
const div3 = document.createElement("div");
div3.innerHTML = "3"; 
const div4 = document.createElement("div"); 
div4.innerHTML = "4";
const routeTable = { "1": div1, "2": div2, "3": div3, "4": div4 };

Copy the code

2. The router

function route() { let number =window.location.hash.substr(1)||1; Let div =routerTable[number.toString()] // Redirect to 404 if (! div) { div = document.querySelector("#div404"); } div.style.display = "block"; InnerHTML = ""; // Empty the container. Container. AppendChild (div); } router(app)Copy the code

Routes are routed once when the hash value changes

window.addEventListener("hashchange", () => {
    route(app);
  });
Copy the code

Route nesting

Multi-level route nesting

const routeTable = {
  "1/1": div11,
  "1/2": div12,
  "1/3": div13,
  "1/4": div14,
};
Copy the code

4. The history

Hash mode, our request path has a #, which is window.location.hash, and history mode has a /, which is window.location.pathname, and the routing table changes accordingly

const routeTable = {
  "/1": div1,
  "/2": div2,
  "/3": div3,
  "/4": div4
};
Copy the code

Hash is not SEO friendly because the hash part is ignored by the browser and therefore not available to the server. History mode is not supported by Internet Explorer 8 and below

The problem with using History is that the page gets refreshed every time it’s requested so it’s slow, so we need to improve it

window.history.pushState(stateObj, "page 2", "bar.html"); //1. Status object 2. Title 3Copy the code

This API can change the referrer, which is used in the HTTP header when the user sends an XMLHttpRequest request, and will change the referrer of any XMLHttpRequest object created by changing state. Because the referrer is the URL that identifies the Document in the Window object represented by this when the XMLHttpRequest object is created.

Note that pushState() definitely does not trigger the hashchange event

And then how do we listen for that change, the answer is different listen, just get the path and re-router it

5. The memory

What if we put the history mode store address in localStorage

Function route (container) {/ / from localStorage path, the default is 1 let number = window. The localStorage. The getItem (" XXX "); if (! number) { number = "/1"; } let div = routeTable[number.tostring ()]; if (! div) { div = document.querySelector("#div404"); } div.style.display = "block"; Container. InnerHTML = ""; container.appendChild(div); } const allA = document.querySelectorAll("a.link"); for (let a of allA) { a.addEventListener("click", e => { e.preventDefault(); const href = a.getAttribute("href"); / / click after change of path in the local window. The localStorage. SetItem (" XXX, "href); onStateChange(href); }); }Copy the code