• View our reviews on Hot Scripts
  • JS Tutorial

Recent Comments

Powered by Disqus

Back to articles

Using Google Analytics Async code for Ajax websites

For faster page loading it is suggested to put all your javascript files to the bottom after all content. But Google Analytics Async Code does not slow down page loading time, because it is working synchronously, thus it can be used in the beginning of the page.

But as code doesn't reload using AJAX, then those pages aren't tracked. To track them you need to call _trackPageview command with your current AJAX state/URL to identify where user has navigated to. As in async syntax, commands are called using _gaq.push method.

Note that URL must start with "/" symbol

So here is a small example of how it would look implemented in AJAX website:

<script type="text/javascript">
function get_content(content)
    $.getJSON("/ajax.php",{url: content, ajax: 'true'}, 
            //getting url example:!News/News-title
            var url = window.location.toString();
            //Getting domain name example:
            var domain = '<?php echo $_SERVER["SERVER_NAME"]; ?>';
            //getting request uri example: /News/News-title
            //Request uri must start with /
            url = url.substring(url.indexOf(domain) + domain.length);
            //calling async trackPageview function with request uri
            _gaq.push(['_trackPageview', url]); 

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);

    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') 
    + '';
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(ga, s);
<!-- We will use url News and News-title for example, where News is menu category  -->
<!-- and News-title is a ID of specific news we want to show -->
<a href='/#!News/News-title' onclick='get_content("News/News-title");'></a>
<div id='content'>

You may also be interested in:

Powered by

blog comments powered by Disqus