Rethinking Dynamic Page Replacing Content
In May of 2012, Chris updated a previous post about dynamic page replacing content. This article is an update to that update, which uses the HTML5 history API for a better user experience.
Here’s a quick recap of the best practices:
- It is possible to “deep link” to specific content.
- The browsers back button and forward button work as expected.
The problem with URL hashes
For one individual user, the existing demo meets the criteria just fine, but URL’s are permanent addresses, and they’re going to be shared.
Consider the following scenario:
I copy the url ‘http://example.com/#awesome-product’, and send it to my friend.
(S)he gets confused/frustrated and swears never to visit example.com again.
THIS IS BAD UX!!
Today, we’ll be improving the existing demo such that the dynamic page replacing content needn’t rely on the hash.
Modernizr for progressive enhancement
Note: The following examples build upon the previous demo. Download the files here to follow along.
Since we’ll be playing with the HTML5 history api, we only need to check the ‘History’ checkbox. Download the custom build here.
Include it in the
<head> of our html file:
Testing for HTML5 history support is super easy:
First, we’re going to set up everything to manipulate the browser’s history, and then we’ll add all the fancy loading provided from the previous demo.
Manipulate the history with HTML5 history API
The HTML5 history.pushState() method allows us to:
- Change the URL
- without a hash
- without a page refresh (this is where the dynamic page replacing content happens)
- Update the browser’s history stack
- so we can navigate through the history with back and forward button clicks.
The pushState() method takes three parameters:
We’re only going to be supplying the URL in this example, but you can learn more about the history API over at the Mozilla Developer Network.
After changing the URL, we’ll want to set up a function to load the content - loadContent() seems like a good name.
And now, we just need to code up the loadContent() function, which is a matter of taking code from the original example.
Handle browser back and forward button clicks
At this point, content is loaded in a fancy ajaxy way, but clicking on your back button won’t take us back… yet. The history API gives us access to the ‘popstate’ event, which fires everytime the history stack changes (read: back and/or forward buttons are clicked.) Anytime this event fires, we just need to call our loadContent() function:
A little homework assignment
At the time of this writing, the popstate event happens on page load in Chrome. This means two requests are being made:
- The original http request for whateverpage.html
- The request made by $.load in our loadContent() function
There are a couple of different ways to handle this, but I’ll let you decide which works best.Edit this Post