Cross-browser jquery ajax history with window.history.pushState and fallback

Binyamin picture Binyamin · Nov 22, 2010 · Viewed 29.2k times · Source

I want to implement a navigation history using jQuery and AJAX in a cross-browser manner. My approach is to use window.history.pushState and fall back to a hash url /#!/url in browsers that do not support window.history.pushState.

For example:

<a href="/home">home</a>
<a href="/about">about</a>
<a href="/contact">contact</a>

On browsers that support window.history.pushState, clicking on one of these links should change address without page refresh to http://domain.com/home, http://domain.com/about etc. When the browser does not support window.history.pushState, it should use a fragment identifier, i.e: http://domain.com/#!/home, http://domain.com/#!/about.


Update: Based on the feedback here I have implemented Ajax SEO (git) that uses jQuery Address for HTML5 History API with old browser fallback to /#!/url.

Answer

Ben Lee picture Ben Lee · Nov 22, 2010
// Assuming the path is retreived and stored in a variable 'path'

if (typeof(window.history.pushState) == 'function') {
    window.history.pushState(null, path, path);
} else {
    window.location.hash = '#!' + path;
}