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:
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:
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.