注意:原文中提到的域名已经无法访问了。
今天了解了一下 History API,写了个页面路由 Demo,支持具名路径。

在线查看 https://nil.red/s/demo/history.html
原理上 path 对应的内容是固定的,通过监听 onpopstate 或者其它触发 path 变动的事件,去更新页面为 path 对应的内容。
部分代码
const $ = document.querySelector.bind(document),
map = {
"/": () => {
$("#view").innerHTML = "Home";
},
"/posts/:id": (params) => {
$("#view").innerHTML = `Post: id=[${params.id}]`;
},
"/about": () => {
$("#view").innerHTML = "About";
},
};
init();
function init() {
jump("/");
}
function jump(path) {
window.history.pushState({ path: path }, null, path);
open(path);
}
function compare(tmp, path) {
/* ... */
}
function open(path) {
for (key in map) {
let _res = compare(key, path);
if (_res === null) {
continue;
} else {
map[key](_res);
}
}
}
$("#menu").addEventListener("click", (e) => {
let path = e.target.getAttribute("data-path");
if (path != null) {
jump(path);
}
});
window.onpopstate = function (e) {
open(e.state.path);
};