JavaScript Development Space

JavaScript Routing with Hash and History API

Routing in JavaScript is about updating the URL and displaying the corresponding content without reloading the page. This improves the user experience by preventing unnecessary page refreshes and preserving application state. There are two common methods for implementing client-side routing: hash-based routing and history-based routing.

Hash-Based Routing

The hash portion of a URL (#) does not cause a full-page reload when changed. This makes it useful for implementing simple client-side routing.

Basic Implementation

To use hash-based routing:

  1. Update the URL with a hash value (#path).
  2. Listen for hash changes using window.addEventListener('hashchange', callback).
  3. Display the corresponding content when the hash changes.

Here's an example:

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Hash Routing</title>
7 </head>
8 <body>
9 <ul>
10 <li><a href="#/home">Home</a></li>
11 <li><a href="#/about">About</a></li>
12 </ul>
13 <div id="app"></div>
14
15 <script>
16 const routes = {
17 '/home': '<h2>Home Page</h2>',
18 '/about': '<h3>About Page</h3>'
19 };
20
21 function routerView() {
22 const hash = location.hash.substring(1) || '/home';
23 document.getElementById('app').innerHTML = routes[hash] || '<h2>404 Not Found</h2>';
24 }
25
26 window.addEventListener('DOMContentLoaded', routerView);
27 window.addEventListener('hashchange', routerView);
28 </script>
29 </body>
30 </html>

Explanation

  • The hash (#) is used to track changes in the URL without reloading the page.
  • location.hash.substring(1) retrieves the current hash value.
  • The routerView function updates the content dynamically based on the hash.

History-Based Routing

The History API (history.pushState and history.replaceState) allows modifying the URL without causing a page reload, enabling more modern single-page application (SPA) behavior.

Basic Implementation

  • Override the default behavior of <a> tags using preventDefault().
  • Use history.pushState() to update the URL.
  • Listen for popstate events to detect browser navigation (back/forward buttons).

Here's an example:

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>History API Routing</title>
7 </head>
8 <body>
9 <ul>
10 <li><a href="/home" class="nav-link">Home</a></li>
11 <li><a href="/about" class="nav-link">About</a></li>
12 </ul>
13 <div id="app"></div>
14
15 <script>
16 const routes = {
17 '/home': '<h2>Home Page</h2>',
18 '/about': '<h3>About Page</h3>'
19 };
20
21 function routerView() {
22 const path = location.pathname;
23 document.getElementById('app').innerHTML = routes[path] || '<h2>404 Not Found</h2>';
24 }
25
26 document.querySelectorAll('.nav-link').forEach(link => {
27 link.addEventListener('click', function(event) {
28 event.preventDefault();
29 history.pushState(null, '', this.getAttribute('href'));
30 routerView();
31 });
32 });
33
34 window.addEventListener('popstate', routerView);
35 window.addEventListener('DOMContentLoaded', routerView);
36 </script>
37 </body>
38 </html>

Explanation

  • Clicking a link updates the URL without a page refresh.
  • history.pushState(null, '', href) modifies the browser history.
  • The popstate event ensures correct navigation when using the browser's back/forward buttons.
  • The routerView function updates the page content based on the current path.

Summary

To implement client-side routing:

  1. Prevent page refresh when changing the URL.
  2. Listen for URL changes (via hashchange or popstate).
  3. Update the page dynamically based on the new URL.

By mastering both hash-based and history-based routing, you can implement robust single-page applications in JavaScript.

JavaScript Development Space

JSDev Space – Your go-to hub for JavaScript development. Explore expert guides, best practices, and the latest trends in web development, React, Node.js, and more. Stay ahead with cutting-edge tutorials, tools, and insights for modern JS developers. 🚀

Join our growing community of developers! Follow us on social media for updates, coding tips, and exclusive content. Stay connected and level up your JavaScript skills with us! 🔥

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.