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:
- Update the URL with a hash value (
#path
). - Listen for hash changes using
window.addEventListener('hashchange', callback)
. - Display the corresponding content when the hash changes.
Here's an example:
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>1415 <script>16 const routes = {17 '/home': '<h2>Home Page</h2>',18 '/about': '<h3>About Page</h3>'19 };2021 function routerView() {22 const hash = location.hash.substring(1) || '/home';23 document.getElementById('app').innerHTML = routes[hash] || '<h2>404 Not Found</h2>';24 }2526 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 usingpreventDefault()
. - Use
history.pushState()
to update the URL. - Listen for
popstate
events to detect browser navigation (back/forward buttons).
Here's an example:
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>1415 <script>16 const routes = {17 '/home': '<h2>Home Page</h2>',18 '/about': '<h3>About Page</h3>'19 };2021 function routerView() {22 const path = location.pathname;23 document.getElementById('app').innerHTML = routes[path] || '<h2>404 Not Found</h2>';24 }2526 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 });3334 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:
- Prevent page refresh when changing the URL.
- Listen for URL changes (via
hashchange
orpopstate
). - 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.