Mike Valstar

Web Development, Programming, Random Thoughts

Twitter Status...

Simple Hashbang URLs and Google

Posted on

websites are increasingly becoming more and more dynamically loaded as opposed to a full page download for every page on a website. This website in particular is using Hashbang (shebang) style page loading to make page transitions more seamless; but this presents a problem both with google search and google analytics. I'll discuss how I manage both of these problems and how you can design a website with seamless page transition as well as tracking these page changes with google analytics.

Simple Hashbang Transition with jQuery

The easiest method to create hashbang style navigation on an existing website without modifying any of your backend code is to do the following using the jQuery .load() method:

Note: this will notwork with older browsers that do not have the onHashchange function, use this jQuery plugin for legacy support.

This will download the content portion (#C, in this example) and replace it on the current page. If you have no javascript that modifies the content of your page, you're done. And because you still use full and proper links on all of your pages google will still be able to index you're entire site and you are able to use permanent and unique URLs for any page.

This however does not lower your server-side load or the html download size. Personally I like to add a post variable to the page specifying that you are doing an ajax request and using that to return a simplified page that can still be used like the above. This can be done by changing the last line in loadPage to: $('#C').load(url + ' #C', {simplePage: true} callback);

Integrating Google Analytics

Google Analytics (by default) works by loading on each page load and using the _gaq.push(['_trackPageview']) command to send the current URL (minus the hash) to google analytics. However you can also call this function yourself to force the page call; so lets add that to our code. And remember to not call the _trackPageview function on your main page unless there is no hash URL available:

Note: you can also use this functionality to track events on your pages such as people using widgets on your site

Download

Full code in jQuery extension format with example available here use the following to initialize: $('#Element').hashbang();

bp_104
comments powered by Disqus
Mike Valstar © 2012