Using Google Analytics to track AJAX requests

青春壹個敷衍的年華 提交于 2019-11-30 21:06:57
Jasper

Well you can use jQuery's AJAX Events to globally listen for AJAX requests and then push an index onto the _gaq array (this seems like the most maintainable approach):

$(document).on('ajaxComplete', function (event, request, settings) {
    _gaq.push(['_trackPageview', settings.url]);
});

Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.

Also note that I have not tested the contents of the arguments passed for global AJAX events.

UPDATE

You can also use $.globalEval() to parse scripts loaded in an AJAX response body: http://api.jquery.com/jquery.globalEval/

success: function(data) {

    var dom = $(data);

    dom.filter('script').each(function(){
        $.globalEval(this.text || this.textContent || this.innerHTML || '');
    });

    $('#mydiv').html(dom.find('#something').html());

}

Source: jQuery - script tags in the HTML are parsed out by jQuery and not executed

The other answers are outdated (as of 2013)- Google's recommends using their new Universal Analytics

You can track page views asynchronously like this:

ga('send', 'pageview', '/my-page');

See: https://developers.google.com/analytics/devguides/collection/analyticsjs/pages#overriding

I use a system that involves requesting the html as plain text, parsing the html first to change all script tags into divs, detach those divs, append the page, then loop through the divs (that are actually scripts) and append their contents to script tags or create script tags with the src on that div. It is very similar to how the history.js framework example does it.

$.get(urlToLoad).promise().done(function(html) {
    var outHTML = html;
    outHTML = outHTML.replace(/<script/ig, "<div class='iscript'").replace(/<\/script/ig, '</script');
    outHTML = $(outHTML);
    var scripts = outHTML.filter('div.iscript').detach();
    $content.html(outHTML);
    scripts.each(function() {
      var $this = $(this), s = document.createElement("script");
      if ($this.attr('src') != "") {
        s.src = $this.attr('src');
      } else {
        s.nodeValue = $this.text();
      }
      $content[0].appendChild(s); // jquery's append removes script tags
    });
}).always(function() {
    $contentclone.replaceWith($content);
    $content.slideDown();
    $contentclone.remove();
});

using this method, you could add the script that does the tracking on each page. I personally prefer to do it on the global page in a way similar to how Jasper suggested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!