Building Simple SPAs with Vanilla JavaScript

Published by Brayan K

Master single-page application architecture using pure JavaScript — routing, views, state management, and professional patterns.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A route change coordinates URL, content and lifecycle

A single-page application usually keeps one document loaded while replacing the view for a different location. A route is not merely a string in the address bar: the visible content, document title, focus, loading state and cleanup of the previous view must agree. Client-side routing does not authorize an action or create a server response for a direct visit.

const routes = new Map([
  ["/", { title: "Home", text: "Choose a task." }],
  ["/tasks", { title: "Tasks", text: "Two tasks remain." }]
]);
function renderPath(root, path) {
  // Unknown routes have an explicit outcome, not an empty screen.
  const page = routes.get(path) ?? { title: "Page not found", text: "Choose a known page." };
  const heading = document.createElement("h2"), body = document.createElement("p");
  heading.textContent = page.title; body.textContent = page.text;
  root.replaceChildren(heading, body);
}
const root = document.createElement("section"); document.getElementById("app").append(root);
renderPath(root, "/tasks");
console.log(root.querySelector("h2").textContent);
renderPath(root, "/missing");
console.log(root.querySelector("h2").textContent);

// ✅ Expected output:
// Tasks
// Page not found

This first example resolves and renders only; it does not modify real history. A route renderer should build fixed DOM and insert data as text. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns unsafe sinks and server authorization. A hidden client route is not a security boundary.

History methods update an entry; they do not run your renderer

pushState adds a same-origin history entry without fetching a new document. replaceState changes the current entry. Neither call dispatches popstate by itself, so an application normally renders explicitly after its own navigation and listens for traversal separately. The following panels run in a fresh ordinary browser origin; the isolated JavaScript editor cannot reproduce that origin contract.

Observe a real pushState without a synthetic popstate

let traversals = 0;
const onPop = () => traversals++;
addEventListener("popstate", onPop);
history.replaceState({ view: "home" }, "", "/");
history.pushState({ view: "tasks" }, "", "/tasks?filter=open#list");
console.log(location.pathname, location.search, location.hash);
console.log(history.state.view, traversals);
removeEventListener("popstate", onPop);

Output

/tasks ?filter=open #list
tasks 0

Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs a normal same-origin History API context; the site editor isolates it.

A real history traversal supplies the activated entry state

history.replaceState({ view: "home" }, "", "/");
history.pushState({ view: "tasks" }, "", "/tasks");
const returned = new Promise(resolve => {
  addEventListener("popstate", event => resolve(event.state.view), { once: true });
});
history.back();
console.log(await returned, location.pathname);

Output

home /

Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs a normal same-origin History API context; the site editor isolates it.

A popstate listener should read the location that is now active and render it; pushing another entry from that listener creates an unwanted back-button loop. Browser behavior around initial load and user interaction can differ, so initialize the current route explicitly. A document can also be restored from the back-forward cache; resource ownership must account for page lifecycle rather than assuming every visit creates a new process.

History state is cloned data and cannot hold a callback

const state = { selected: ["a"] };
history.replaceState(state, "", "/tasks");
state.selected.push("b");
console.log(history.state.selected.join(","));
try { history.pushState({ callback() {} }, "", "/other"); }
catch (error) { console.log(error.name); }
console.log(location.pathname);

Output

a
DataCloneError
/tasks

Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs a normal same-origin History API context; the site editor isolates it.

Cross-origin URLs are rejected before changing the route

try { history.pushState({}, "", "https://other.example.test/tasks"); }
catch (error) { console.log(error.name); }
console.log(location.pathname);

Output

SecurityError
/

Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs a normal same-origin History API context; the site editor isolates it.

Keep history state small and serializable. Do not store secrets in URLs or assume history is a durable database. Search parameters and fragments have separate meanings; decide which ones your route owns. A hash router can work with a simpler static host because the fragment is not sent in the HTTP request, but it still needs accessibility, loading and back/forward behavior.

Intercept only the navigation the application owns

function shouldHandle(event, anchor, currentURL) {
  if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey)
    return false;
  if (anchor.hasAttribute("download") || (anchor.target && anchor.target !== "_self")) return false;
  const destination = new URL(anchor.href, currentURL), current = new URL(currentURL);
  return destination.origin === current.origin && destination.pathname.startsWith("/app/") && !destination.hash;
}
const anchor = document.createElement("a"); anchor.href = "https://site.example.test/app/tasks";
const click = { button: 0, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, defaultPrevented: false };
console.log(shouldHandle(click, anchor, "https://site.example.test/app/"));
console.log(shouldHandle({ ...click, ctrlKey: true }, anchor, "https://site.example.test/app/"));
anchor.target = "_blank";
console.log(shouldHandle(click, anchor, "https://site.example.test/app/"));

// ✅ Expected output:
// true
// false
// false

This policy deliberately owns only paths below /app/ and leaves fragment links alone. It is a policy example, not a complete site router. In a delegated click listener, locate the intended anchor with closest, apply the policy, and only then preventDefault and navigate. Retain real href values so links can be copied and opened in another tab. Events owns event propagation and delegation.

const url = new URL("https://site.example.test/app/tasks?q=first+draft&tag=a&tag=b");
console.log(url.pathname);
console.log(url.searchParams.get("q"));
console.log(url.searchParams.getAll("tag").join(","));

// ✅ Expected output:
// /app/tasks
// first draft
// a,b

Decoding and validation remain separate. A decoded query string is still untrusted input, and a repeated parameter needs an explicit policy. Keep the canonical location and application state consistent; do not secretly maintain a second incompatible route in a global variable.

A late view must not overwrite a newer navigation

let generation = 0, visible = "", release;
async function show(load) {
  const token = ++generation;
  const text = await load();
  if (token === generation) visible = text;
}
const old = show(() => new Promise(resolve => { release = resolve; }));
await show(async () => "new");
release("old"); await old;
console.log(visible);

// ✅ Expected output:
// new

Cancellation can save work when a loader cooperates, while a generation check protects the visible result even when it does not. Neither rolls back server effects. JavaScript Performance Optimization Techniques owns cancellation and scheduling contracts; this page applies result ownership to navigation. Show a loading state and a useful failure state, and avoid leaving the previous heading paired with an unrelated new URL.

const root = document.createElement("section"), heading = document.createElement("h2");
heading.textContent = "Tasks"; heading.tabIndex = -1;
root.append(heading); document.getElementById("app").append(root);
document.title = "Tasks";
heading.focus();
console.log(document.title, document.activeElement === heading);

// ✅ Expected output:
// Tasks true

tabIndex -1 lets code focus the heading without adding it to the ordinary Tab sequence. Actual focus and scroll behavior depend on the application and assistive technology, so test them. The browser’s page title, visible heading and accessible navigation state should describe the new view. Back/forward scroll restoration also needs a deliberate policy; moving every visit to the top can erase a useful return position.

Direct visits and cleanup still involve the host

A history-based /tasks route needs the host to return the application document for that navigation. That fallback should not turn a missing JavaScript file or API endpoint into a 200 HTML response. Test a pasted deep link, reload, unknown path and missing asset on the built deployment. Deploying JavaScript Apps (CDN, Minification, Bundling) owns response policies and asset caching.

const listeners = new Set();
function subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); }
let notifications = 0;
const cleanup = subscribe(() => notifications++);
for (const fn of listeners) fn();
cleanup();
for (const fn of listeners) fn();
console.log(notifications, listeners.size);

// ✅ Expected output:
// 1 0

Dispose timers, listeners and in-flight work owned by the view when its lifetime ends. Do not close a shared connection the router merely borrowed. Building Reusable UI Components with Pure JS owns component mount/update/dispose contracts. A client-side not-found view is useful to a reader but does not, by itself, make the server emit HTTP 404.

Guided exercise: keep unknown routes explicit

Complete the lookup, fallback and DOM assignment. The result should name a missing route without parsing route data as HTML. This exercise does not alter browser history.

const pages = new Map([["/", "Home"], ["/tasks", "Tasks"]]);
function headingFor(path) {
  const title = pages.___(path) ?? "Page not found"; // 👉 replace ___ with get
  const heading = document.createElement(___); // 👉 replace ___ with "h2"
  heading.___ = title; // 👉 replace ___ with textContent
  return heading;
}
console.log(headingFor("/tasks").textContent);
console.log(headingFor("/unknown").textContent);

// ✅ Expected output:
// Tasks
// Page not found

Brief: own asynchronous page transitions explicitly

Implement mountPages(root, adapter, pages). The root is an empty HTML element. The adapter provides read, push and subscribe; subscribe returns a cleanup function. Page registrations have unique simple paths such as / or /tasks, a nonempty title and a render(signal) function returning a detached HTML element, possibly asynchronously. Snapshot registrations when mounting. These are trusted application adapters and ordinary registrations, not hostile getters.

Expose refresh, navigate and idempotent dispose. Mounting does not automatically render: the caller awaits refresh. navigate validates a simple local path, pushes only when it differs from the current one, then refreshes explicitly. Unknown routes show Page not found. A started transition aborts the previous signal, displays Loading and accepts only its own latest result. Success updates title and focuses an h2; a current failure shows a useful failure heading. Disposal unsubscribes, aborts and clears the owned root; late results must not mutate it.

function mountPages(root, adapter, pages) {
  if (!(root instanceof HTMLElement) || root.childNodes.length ||
      !adapter || !["read", "push", "subscribe"].every(key => typeof adapter[key] === "function") ||
      !Array.isArray(pages) || pages.length === 0)
    throw new TypeError("empty root, navigation adapter and pages are required");
  const registry = new Map();
  for (let i = 0; i < pages.length; i++) {
    const page = pages[i];
    if (!Object.hasOwn(pages, i) || !page || typeof page.path !== "string" ||
        !/^\/(?:[a-z]+(?:-[a-z]+)*)?$/.test(page.path) || registry.has(page.path) ||
        typeof page.title !== "string" || page.title.trim() === "" || typeof page.render !== "function")
      throw new TypeError("invalid page registration");
    registry.set(page.path, { title: page.title.trim(), render: page.render });
  }
  let disposed = false, generation = 0, current = null;
  async function refresh() {
    if (disposed) return "disposed";
    const token = ++generation;
    current?.abort();
    const aborter = new AbortController(); current = aborter;
    const path = adapter.read(), page = registry.get(path);
    const heading = document.createElement("h2"); heading.tabIndex = -1;
    if (!page) {
      heading.textContent = "Page not found"; root.replaceChildren(heading);
      document.title = "Page not found"; heading.focus(); return "missing";
    }
    const loading = document.createElement("p"); loading.setAttribute("role", "status"); loading.textContent = "Loading";
    root.replaceChildren(loading);
    try {
      const content = await page.render(aborter.signal);
      if (disposed || token !== generation) return "stale";
      if (!(content instanceof HTMLElement) || content.parentNode !== null ||
          content === root || content.contains(root) || content.ownerDocument !== root.ownerDocument)
        throw new TypeError("render must return a detached HTML element");
      heading.textContent = page.title; root.replaceChildren(heading, content);
      document.title = page.title; heading.focus(); return "shown";
    } catch (error) {
      if (disposed || token !== generation) return "stale";
      heading.textContent = "Could not open page"; root.replaceChildren(heading);
      document.title = "Page unavailable"; heading.focus(); return "failed";
    }
  }
  const unsubscribe = adapter.subscribe(() => { void refresh(); });
  if (typeof unsubscribe !== "function") throw new TypeError("subscribe must return cleanup");
  return Object.freeze({
    refresh,
    async navigate(path) {
      if (disposed) return "disposed";
      if (typeof path !== "string" || !/^\/(?:[a-z]+(?:-[a-z]+)*)?$/.test(path))
        throw new TypeError("path must be one simple local route");
      if (path !== adapter.read()) adapter.push(path);
      return refresh();
    },
    dispose() {
      if (disposed) return false;
      disposed = true; generation++; current?.abort(); unsubscribe(); root.replaceChildren();
      return true;
    }
  });
}
function memoryNavigation(initial = "/") {
  let path = initial;
  const listeners = new Set(), pushed = [];
  return {
    pushed, read: () => path,
    push(next) { path = next; pushed.push(next); },
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
    traverse(next) { path = next; for (const fn of listeners) fn(); },
    listenerCount: () => listeners.size
  };
}
const root = document.createElement("section"); document.getElementById("app").append(root);
const navigation = memoryNavigation();
let release;
const makeContent = text => { const p = document.createElement("p"); p.textContent = text; return p; };
const router = mountPages(root, navigation, [
  { path: "/", title: "Home", render: async () => makeContent("Welcome") },
  { path: "/slow", title: "Slow", render: () => new Promise(resolve => { release = resolve; }) },
  { path: "/tasks", title: "Tasks", render: async () => makeContent("Two tasks") }
]);
console.log(await router.refresh(), root.querySelector("h2").textContent);
const old = router.navigate("/slow");
console.log(await router.navigate("/tasks"), document.title);
release(makeContent("Old view"));
console.log(await old, root.querySelector("h2").textContent);
console.log(await router.navigate("/missing"), document.title);
console.log(router.dispose(), router.dispose(), navigation.listenerCount(), root.childNodes.length);

// ✅ Expected output:
// shown Home
// shown Tasks
// stale Tasks
// missing Page not found
// true false 0 0

The recording adapter tests controller behavior, not native history. A browser adapter can read location.pathname, push with history.pushState and subscribe to popstate using the exact callback it removes. The separate real-history panels above check those API behaviors. Authentication, actual network loading, server fallback rules, scroll restoration and assistive-technology behavior still need integration checks.

Practice quiz

What does pushState do by itself?

  • Adds a history entry without running your renderer
  • Dispatches popstate immediately
  • Fetches the new HTML document
  • Authorizes the route

Answer: Adds a history entry without running your renderer. The application renders after its own push; traversal is observed separately.

What does this complete program print? const routes=new Map([["/","Home"]]);console.log(routes.get("/missing")??"Page not found");

  • Home
  • Page not found
  • undefined
  • null

Answer: Page not found. An unknown route needs an explicit visible outcome.

Which click should a normal client router leave to the browser?

  • An owned unmodified link
  • A plain left click to a known route
  • A Ctrl-click intended for another tab
  • Its own navigate call

Answer: A Ctrl-click intended for another tab. Preserve standard browser navigation affordances.

What does this complete program print? let version=0;const old=++version;const current=++version;console.log(old===version,current===version);

  • true true
  • true false
  • false false
  • false true

Answer: false true. Only the latest transition token owns the current result.

What must the host support for a pasted history-based deep link?

  • Returning the appropriate application document for that navigation
  • Changing the URL to a fragment automatically
  • Running the client click handler first
  • Returning HTML for every missing asset

Answer: Returning the appropriate application document for that navigation. A direct visit reaches the server before the client router runs.

What does this complete program print? const root=document.createElement("div");const h=document.createElement("h2");h.textContent="Tasks";root.replaceChildren(h);console.log(root.textContent);

  • undefined
  • Tasks
  • <h2>Tasks</h2>
  • null

Answer: Tasks. Text content exposes the visible heading text.

What does this complete program print? const listeners=new Set();const fn=()=>{};listeners.add(fn);listeners.delete(fn);console.log(listeners.size);

  • 1
  • 2
  • 0
  • undefined

Answer: 0. Cleanup removes the same registered callback.

What does a client-side not-found heading establish?

  • The server returned HTTP 404
  • The asset cache was cleared
  • The user is authenticated
  • The client chose a not-found view

Answer: The client chose a not-found view. The HTTP status is a separate server response property.

Continue this course

Related lessons