You want to use XMLHttpRequests (AJAX) to avoid unnecessary page loads, hence reducing network traffic and therefore speeding up you web-app, you probably already do this in your web-apps. However, before the advent of the HTML 5 History API there was a problem with this otherwise smart approach to building web-apps. When a page updated it's content this would not be reflected in the browser history and you had to do a lot of work to make the back and forward buttons work as expected. Thanks to the HTML 5 History API this is now much simpler. In this article I'll explain an approach to "mimicking" a common server-side approach to "dynamic" page loading using parameters in the url, while retaining the functionality of the browser history. Take a look at the demo.
What this typical AJAX demo does is pretty basic:
- At startup it loads a page depending upon the presence of a parameter.
- When you click a link (at the top), it fetches and swaps the content of the "content" holder of the main page.
|Pushed history items|
However, after having clicked the links you'll also notice that the back and forward buttons are working, without actually navigating you away from the main page, like the're integrated with the app. Also, items are "pushed" onto the browser history, making it possible to navigate directly to a previously loaded page. It's just updating the content of the content box when you click a link, not the entire page. This is what happens:
- When a link is clicked the new content is fetched using a XMLHttpRequest.
- The current content is replaced and the browser history is updated.
All of these operations are accomplished using only three (3) API calls:
- The «onpopstate» event allows us to listen to events fired when the history is being navigated, like when using the back button. (see line 57'ish in the demo code for how this is handled).
- The «replaceState» method allows us to replace the current state in the browser history. This is used to create a state when for example on initial page load.
- The «pushState» method allows us to add things to the history stack (it's a stack, hence push and pop).
Now, this does not work in all browsers (IE..duh!) and as of writing this post still has «Working Draft» status. However, support is pretty good and when Microsoft finally adds support in IE 10, all major browsers will support the History API.
Take a look at the demo and the source code (which is heavily commented) and feel free to use the source freely.