What does JavaScript Routing buy you? What does JavaScript Routing buy you? asp.net asp.net

What does JavaScript Routing buy you?


Routing is a way of organizing and managing application states. A routing framework in JavaScript helps you to change the state of the application--perhaps moving from one admin panel section to another--while maintaining application persistence.

If you want to navigate from one application state, e.g. /admin/users, to another, e.g. /admin/orders, you could use a normal link as you suggest. But then you're going to cause the browser to navigate from one HTML page to another. This is, obviously, the normal way that one navigates around the Web. But in a JavaScript application, this is pretty inefficient!

If you're running a complex in-browser application in JavaScript, then that app needs to do a lot of work when it's starting up. It registers event handlers, loads and executes a bunch of JavaScript, and sometimes renders the entire page interface dynamically (in the case of ExtJS and a few other libraries). That's a lot of extra work for the browser to set up a JavaScript application at /admin/orders that has a lot in common with the one at /admin/users. A more efficient way is for the link to fire an event that the application monitors, and for the application to respond by changing the application's state--perhaps by removing or hiding the users view and replacing it with an orders view. Routing is a way of representing these different interfaces, using a token--usually a URL fragment like /admin/users--to keep track of where the user is in your interface.

This allows the application to maintain the dynamic object model that it's already burned time and used memory to create. It makes the user interface respond more speedily, and, if you're using URL history management via a hashtag or pushState, it allows the user to navigate around your app using the back and forward buttons of their browser, without reloading every asset on the page every time and wiping your application state. URL management also allows deep linking to some page in the application: on load, your app's router examines the route string that it receives, tokenizes it, and loads up the interface you've specified in your routing table.

Routing is not required in order to manage persistence, but it's a good way of organizing your persistent states. Often, a routing system goes hand in hand with URL history management, like Davis.js. But there are also routing libraries that don't mess with the URI, that maintain an abstract tokenized state which you can use or display as you see fit, like Crossroads.js.