Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Created May 25, 2025 19:18
Show Gist options
  • Save ggorlen/5ad4254a82ec9b805a0026b941e38900 to your computer and use it in GitHub Desktop.
Save ggorlen/5ad4254a82ec9b805a0026b941e38900 to your computer and use it in GitHub Desktop.
minimal vanilla SPA history router
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
<script>
const nav = `<a href="/">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>`;
const routes = {
"/": `<h1>Home</h1>${nav}<p>Welcome home!</p>`,
"/about": `<h1>About</h1>${nav}<p>This is a tiny SPA</p>`,
};
const render = path => {
document.querySelector("#app")
.innerHTML = routes[path] ?? `<h1>404</h1>${nav}`;
document.querySelectorAll('#app [href^="/"]').forEach(el =>
el.addEventListener("click", evt => {
evt.preventDefault();
const {pathname: path} = new URL(evt.target.href);
window.history.pushState({path}, path, path);
render(path);
})
);
};
window.addEventListener("popstate", e =>
render(new URL(window.location.href).pathname)
);
render("/");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment