DEV Community

Dhruvang Gajjar
Dhruvang Gajjar

Posted on

A routing system in JavaScript for Single Page Application

๐ŸŒ Building a Simple Routing System in Vanilla JavaScript for SPAs

In the world of Single Page Applications (SPAs), managing routes without a framework can seem daunting. But with Vanilla JavaScript, you can create a simple yet powerful routing system! ๐Ÿš€


Hereโ€™s a quick guide to get you started:

1๏ธโƒฃ Understand the Basics of Routing

Routing in an SPA involves mapping a URL to a specific view or content. Instead of reloading the page, the app dynamically updates the content based on the URL.

2๏ธโƒฃ Core Concepts

  • Hash-based Routing: Uses window.location.hash (e.g., /#/home). It's simple and doesn't require server configuration.
  • History API: Leverages pushState and popstate for cleaner URLs (e.g., /home).

3๏ธโƒฃ Steps to Build

Step 1: Set Up Your HTML Structure

<div id="app">
  <nav>
    <a href="#/">Home</a>
    <a href="#/about">About</a>
    <a href="#/contact">Contact</a>
  </nav>
  <div id="view"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Router

class Router {
  constructor(routes) {
    this.routes = routes;
    this.init();
  }

  init() {
    window.addEventListener("hashchange", () => this.handleRouteChange());
    this.handleRouteChange();
  }

  handleRouteChange() {
    const currentPath = window.location.hash.slice(1);
    const route = this.routes[currentPath];
    if (route) {
      route();
    } else {
      this.routes["/404"]();
    }
  }
}

// Usage
const router = new Router({
  "/": () => (document.getElementById("root").innerHTML = "Home Page"),
  "/about": () => (document.getElementById("root").innerHTML = "About Page"),
  "/404": () => (document.getElementById("root").innerHTML = "404 Page"),
});

Enter fullscreen mode Exit fullscreen mode

4๏ธโƒฃ Enhancements

  • Use the History API for cleaner URLs.
  • Lazy-load content or templates for better performance.
  • Add 404 and fallback routes for improved user experience.

Why Build This Yourself?

  • Deep Understanding: Learn the mechanics behind routing.
  • Flexibility: Customize it to your needs without the constraints of a library.
  • Performance: Avoid the overhead of external dependencies.

๐Ÿ’ก Pro Tip: If you're building a larger app, consider modularizing your code and handling edge cases like query parameters or nested routes.

Have you ever built your own routing system? Share your experience in comments! ๐Ÿ‘‡

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more โ†’

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay