Blog

Maintain browser history with pages loaded dynamically by AJAX

A solution for adding dynamic pages to the browser history while using Ajax.

Loading content from a page using Ajax is relatively simple using JQuery. Chris Coyier’s Ajax Load Container Contents does a great job explaining this process.

But when this content is loaded, the URL stays the same. Clicking through dozens of links changes the page content but when you click the browser back button it does not work as you’d expect it to.

The problem we have is that new pages haven’t physically been navigated to but instead had their content loaded into the current page dynamically using Ajax. The browser doesn’t register this as a page change. So in the history, it will still only contain the homepage (if that’s where you landed).

This will also prove problematic when sharing pages socially. Dynamically loading content and then sharing the page will not share the updated page. Instead, the URL shared will load its static content.

Introducing Hashes

I have written a function that combines Ajax loading and adding the dynamic page to the browser history. Therefore clicking through multiple pages loads new content into the desired section. It will then change the hashtag text to represent the new content on the page. Clicking back and forth through the browsers history will reload older content and change hashtag.

An intelligent aspect of this function is sharing a page with a hashtag will load the hashtag's page with the dynamic content loaded.

The Mark Up

The actual URL of the blog is contained within the ‘data attribute’. While a hashed version of the URL is contained within the ‘href attribute’. By setting the ‘href attribute’ to a hash string, the browser will not deviate to another page, but will just add this hash string to the end of the current URL. If a hash strong exists in the URL, it will be replaced with this new one. It will become apparent in the JavaScript why the structure is like this.

Here below is an example of a navigation with hashed links ready for Ajax loading with hash changes.

This is a very basic example of Hash change events with Ajax loading. It can be developed further to include subtle animation of content as it is loaded into the current page. Just include the latest JQuery library above this script of you do want to use this.