hash & History
修改 url 的 hash, 并不会触发整个页面的重新渲染。(浏览器的兼容性比较好)
hash
<div>
<a id="home" href="#/home"> home</a>
<a id="about" href="#/about">about</a>
</div>
<div class="content"></div>
const contentEl = document.querySelector(".content");
// hashchange, 监听 url hash 的变化。
window.addEventListener("hashchange", () => {
// console.log("url hashchange...");
contentEl.innerHTML = location.href;
});
history
H5 提供的功能, 通过 history 对象修改 url, 并不会触发整个页面的重新渲染。
<div>
<a id="home" href="/home"> home</a>
<a id="about" href="/about">about</a>
<button id="random">Random</button>
</div>
<div class="content"></div>
const contentEl = document.querySelector(".content");
const homeEl = document.getElementById("home");
const aboutEl = document.getElementById("about");
homeEl.addEventListener("click", (e) => {
e.preventDefault();
history.pushState({}, "", homeEl.getAttribute("href"));
contentEl.innerHTML = location.href;
});
aboutEl.addEventListener("click", (e) => {
e.preventDefault();
history.pushState({}, "", aboutEl.getAttribute("href"));
contentEl.innerHTML = location.href;
});
document.getElementById("random").addEventListener("click", () => {
const url = location.href + Math.floor(Math.random() * 10);
history.pushState({}, "", url);
contentEl.innerHTML = url;
});