我正在改变网站的一大部分,以使用jQuery Address'深度链接AJAX功能。我正在使用mysite.com/#!/page1/subpage/
之类的URI等等。
我已经阅读了一些关于使用_gaq.push()
功能跟踪流量的信息,但我想知道是否可以采用更传统的方式来实现...
每个AJAX请求调用一个PHP函数,该函数构建一个页面并将其返回到<HTML>
包装器中,这样我就可以轻松定义自定义页面标题等等。
如果我将分析代码放在该页面上,jQuery调用该页面会触发它来跟踪访问吗?
答案 0 :(得分:15)
那么你可以使用jQuery的AJAX事件来全局监听AJAX请求,然后将索引推送到_gaq
数组(这似乎是最易维护的方法):
$(document).on('ajaxComplete', function (event, request, settings) {
_gaq.push(['_trackPageview', settings.url]);
});
请注意,.on()
是jQuery 1.7中的新增内容,在这种情况下与.bind()
相同。
另请注意,我还没有测试为全局AJAX事件传递的参数的内容。
<强>更新强>
您还可以使用$.globalEval()
来解析在AJAX响应正文中加载的脚本: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());
}
来源:jQuery - script tags in the HTML are parsed out by jQuery and not executed
答案 1 :(得分:5)
其他答案已过时(截至2013年) - Google建议使用新的Universal Analytics
您可以像这样异步跟踪网页浏览:
ga('send', 'pageview', '/my-page');
请参阅:https://developers.google.com/analytics/devguides/collection/analyticsjs/pages#overriding
答案 2 :(得分:2)
我使用的系统涉及将html作为纯文本请求,首先解析html以将所有脚本标记更改为div,分离这些div,附加页面,然后循环遍历div(实际上是脚本)并附加它们内容到脚本标签或使用该div上的src创建脚本标签。它与history.js框架示例的工作方式非常相似。
$.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();
});
使用此方法,您可以添加在每个页面上执行跟踪的脚本。我个人更喜欢在类似于Jasper建议的方式在全局页面上这样做。