World’s Smallest JavaScript Router

In a recent project, actually still in-progress project, I needed a small JavaScript router that would fit the following requirements:

  1. Be Tiny
  2. Allow bookmarking of sub views
  3. Assume jQuery as the only available library

I poked around the interwebs, and used Microjs to see if one of them fits what I’m looking for. None quite did, so I did what any other developer usually does, wrote one myself!

Another point to make is that, all the HTML required was already loaded into the page. I didn’t need any AJAX at all. I wanted it to be a completely client-side solution.

Using Hashes

One requirement I wanted was the ability to bookmark certain sub views of the page. With that comes modifying the URL, and handling showing that view when loading into the page.

A way to do that is using hashes on the URL, specifically window.location.hash. That gives us the ability to grab what’s after that hash symbol in the window’s location. Using anchors with hashes in the href will allow us to specify specific routes those links will trigger.

Capturing Routes

Now that I had a way to allow bookmarking of routes, I needed a way to capture when a route would change. Luckily, the  window object has a  onhashchange (docs) event that does just that.

Now when an anchor is clicked to trigger a route, I capture it using that event, then I can kind of whatever I want from then on. We can use jQuery to capture that event as well.

It’s starting to look like a real router. If there’s no hash, I just assumed ‘index’ to make it have an “MVC” feel.

Handling Routes

We have a way to trigger routes, capture them, let’s do something with it. In the code example above, you obviously could just handle it all in that one event handler. That could get messy with if statements, or a big switch, or maybe some object magic. There’s an easier way, events!

jQuery gives us the ability to define custom events that we can trigger when we want to. Taking that into account, routes can be translated into custom jQuery events like so:

Then it’s simple to handle them:

The neat thing about using events is that it can be done anywhere in your JavaScript as long as it is on the same page. It also follows the Open/Closed Principle in that events can be added without having to modify the base functionality.