Chapter 6
The trick is based on the fact that we can modify parts of the URL in a browser's
address bar, those after the # character without triggering a reload of the currently
displayed page. This part of the URL is called the URL fragment. By changing the
URL fragment, we can add new elements to the browser's history stack (the window.
history object). The back and forward buttons rely on the browser's history. So if we
manage to get the history right, the navigation buttons will work as expected.
Let's consider a set of typical URLs often used in CRUD-like applications. Ideally,
we would like to have a URL pointing to a list of items, an edit form for an item, a
form for new items, and so on. Taking the administration of users (from our sample
SCRUM application), as an example, we would typically have the following distinct
partial URLs:
- /admin/users/list – This URL shows a list of existing users
- /admin/users/new – This URL shows a form to add a new user
- /admin/users/[userId] – This URL shows a form to edit an existing user
with ID equal to [userId]
We could translate these partial URLs to full URLs with fragments in a single-page
web application using the # trick as follows:
- http://myhost.com/#/admin/users/list
- http://myhost.com/#/admin/users/new
- http://myhost.com/#/admin/users/[userId]
URLs pointing to inner parts of a single-page web applications, in this way are often
referred to as "hashbang URLs".
Having set up the preceding URL scheme, we can change the URL in the browser's
address bar without fully reloading the page. The browser will pick up different
URLs (with the same prefix but different URL fragment after the # character) to drive
its history and back/forward buttons. At the same time, it won't issue any calls to the
server if the only changing part is the URL fragment.
Of course, changing the URL scheme is not enough. We need to have some
JavaScript logic that will observe URL fragment changes, and modify the client-side
state of the application accordingly.
HTML5 and the history API
As users, we love simple, memorable, and easy-to -bookmark URLs, but the
hashbang tricks just described, make URLs excessively long and to be frank quite
ugly. Fortunately there is an HTML5 specification that addresses this problem: The
history API.