Implementing HTML5 History API into your AJAX-Based Website

Programming


With the release of HTML5, the page address can be changed without reloading or using location.hash() function as was the case before. Nowadays, the history API is supported by almost all popular browsers except Internet Explorer (and this is not surprising :)). 

The main benefits of using history API are:


  • If you are using a simple hashchange, the part of address after “#” is not being sent to the server and that why it is difficult to go to such a link. You don’t have to worry about this if you are using history API.

  • To track hashchanges, you have to use setInterval()function, and compare the current hash with the one saved before. You can set event handlers on navigation buttons in history API.

  • Using history API works much better for SEO. Search engines can index the pages much more effectively.

Syntax:

history.pushState([state object],[title],[URL])

Parameters:

- state object – state variable. Useful in saving the action, which is needed to fire when pressing the browser navigation buttons
- title – link title in history
- URL – the very address that will be displayed in the address bar.

Using this function, you can add record in browser history. You can check this right now in the browser console (for example Google Chrome JS console):

history.pushState(null,null,"testaddress")

If the address bar contains only the name of the site, "#" or a GET request, the address will be “ukietech.com / testaddress “. If the address is just a path to the file or imitation of using mod_rewrite, for example “ukietech.com /users/user1”, then the address will change only after the last slash, so the new address will look like “ukietech.com / users / newAddress”.

To check browser support you can use the following code, which will log “true” or “false” into console:

var supportsHistoryAPI=!!(window.history && history.pushState);console.log(supportsHistoryAPI);

Example of using history.pushstate and Ajax requests:

html:

<nav>
                <li><a href="/main/">Main page</a></li>
                <li><a href="/items/">Items</a></li>
                <li><a href="/orders/">Orders</a></li>
                <li><a href="/about/">About</a></li>
</nav>

js:

$('nav li a').click(function(e) {
             e.preventDefault();

             var href = $(this).attr("href");
                           
              $.ajax({
                           url : href,
                           type : GET,
                           success : function(data){
                                         wrapper.html(data);
                           }
              });               

            history.pushState('', 'New URL: '+href, href);
           
});

This script will fire on click event on anchor element. Content will be loaded from the page, which is set in the href attribute of anchor, and inserted into container as html. Page address will be also changed via history.pushState function.

To make browser navigation buttons react in a right way, you can use this:

window.onpopstate = function(event) {
                if(event.state === ''){
                             var href = location.pathname,
                                           wrapper = $(".main_container");
                      $.ajax({
                                …same code as above…
                                   });
                }
        };

As for Internet Explorer, you can use old hashchange method for this purpose until it will be supported.

I believe this information will be useful for developers who want to be on the cutting edge and up-to-date with the latest trends.

See also: Semantics in HTML5

Comments