URLs without a reload in JavaScript
pushState changes the address bar; popstate tells you about back.
function navigate(path, { push = true } = {}) {
if (push) {
history.pushState({ path }, "", path);
} else {
history.replaceState({ path }, "", path);
}
render(path);
}
function render(path) {
const [, lang, tour] = path.split("/");
document.title = tour ? `${lang} - ${tour}` : lang || "typestar";
return { lang, tour };
}
window.addEventListener("popstate", (event) => {
render(event.state?.path ?? location.pathname);
});
How it works
pushStateadds an entry,replaceStaterewrites the current one.- The popstate handler is where you re-render.
- The URL must stay same-origin.
Keywords and builtins used here
constdocumentelsefunctionifreturnwindow
The run, in numbers
- Lines
- 18
- Characters to type
- 425
- Tokens
- 133
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 76 seconds.
Step 1 of 2 in URLs & formatting, step 11 of 13 in The browser.