Crafting a dynamic website often requires routing, the process of matching a URL with the correct page or action. Frameworks like React, Angular, or Django handle this seamlessly, but what if you want to implement HTML routing without relying on these? It's possible with a bit of JavaScript, HTML, and a simple understanding of browser history management. Let's explore this route—pun intended.

Before we dive in, let's understand why you might want to do this. HTML routing allows for cleaner URLs, better user experience, and improved SEO. It also offers a taste of full-stack development—something no framework can take away from you.

Setting Up: The Basic Structure
First, we need to set up a basic HTML structure with the div elements where our content will dynamically load. Here's a simple setup:

<div id="app"></div>
Pure HTML Routing

While it's possible to implement routing purely with HTML and JavaScript without any libraries, it becomes verbose and repetitive. Still, it's good to understand how it works at its core.
Let's say you have three pages—'home.html', 'about.html', and 'contact.html'. In 'index.html', we'll handle the routing:
- Include all three pages in 'index.html'.
- Use JavaScript to show/hide these sections based on the URL.

Leveraging Hashchange Event
Another way to achieve routing is by listening to the hashchange event in JavaScript. This event fires whenever the hash part of the URL changes. We can use this to load different content.
Here's a simple example:

- Include all your HTML pages in your main 'index.html'.
- Add an event listener for the hashchange event. In this event, show/hide relevant content based on the hash part of the URL.
Improving Routing with HTML5 History API




















While hash-based routing works, it's not pretty (nor 'pretty URLs'). HTML5 History API allows for cleaner URLs. This API lets us manipulate the browser history stack, enabling us to change the URL without reloads.
Forward and Back Buttons
One caveat is that back/forward buttons won't work as expected because the URL doesn't represent a real state. To fix this, we should push a state and pass relevant data to make the back/forward buttons work correctly.
Using pushState
HTML5 History API's pushState method allows us to add new entries to the browser history stack. This method takes three arguments: state (optional), title (ignored), and URL.
Remember, browser support might be an issue with this approach. Internet Explorer doesn't support this API. Always check your target browsers before diving into this method.
HTML routing without a framework can be a challenging but rewarding experience. It expands your understanding of how websites work under the hood. So, go ahead, experiment, and happy coding! And when you're ready for more complexity, you'll appreciate the structure that frameworks provide.