CodeBlanks Logo Icon CodeBlanks

SPA routing basics

JavaScript course · Advanced · Lesson 82/100

Learn simple client-side routing that works without page reloads with the History API.

SPA routing

A single-page application (SPA) changes views without reloading the page. The History API is the backbone of this: intercept link clicks, update the URL with pushState, and swap the view with JavaScript.

link.addEventListener('click', (event) => {
  event.preventDefault();
  history.pushState({}, '', link.href);
  render(link.href);
});

To support the back and forward buttons, you also add a popstate listener that calls render.

Catch link clicks

A link's default behavior is to reload the page. In an SPA you stop that with event.preventDefault(), then update the URL with pushState and draw the view yourself.

link.addEventListener('click', (event) => {
  event.preventDefault();
  const path = link.getAttribute('href');
  history.pushState({ path }, '', path);
  render(path);
});

Each click now adds a new history entry, so the back button works naturally.

Exercise Write a navigate function

Write a function named navigate(path). Inside it, call history.pushState with the state { path }, an empty string as the second argument and path as the third. Then call render(path) to update the view.

Show example solution
function navigate(path) {
  history.pushState({ path }, '', path);
  render(path);
}

Test yourself

  1. What is the benefit of SPA routing with the History API?

    • The view changes without reloading and back or forward works
    • Full HTML is downloaded from the server each time
    • The browser history is cleared
    • The URL always stays the same
    Show answer

    The view changes without reloading and back or forward works — Correct! An SPA routes without reloading using the History API.

  2. Stop the reload on click

    link.addEventListener('click', (event) => {
      ____;
      history.pushState({}, '', link.href);
    });
    Show answer
    link.addEventListener('click', (event) => {
      event.preventDefault();
      history.pushState({}, '', link.href);
    });
  3. Match the SPA routing steps

    click
    pushState is called
    pushState
    updates the URL
    popstate
    catches back or forward
    view swap
    content is changed

All lessons in Advanced