我有一个企业交易网站。我在我网站的每个jsp中都包含了Google analytic's
代码。现在的问题是,因为在我的网站中,一些页面被包含在其他页面中,而不仅仅通过ajax调用和更改div内容使用框架。因此,当在同一页面中加载新页面时,Google Analytic将不会被调用,因为整个页面未加载,并且浏览器仅考虑页面加载以加载js,而不是帧更改。任何人都可以为此建议解决方案
答案 0 :(得分:1)
最简单的解决方案是使用全局变量,如下所示:
if (! window.googleAnalytics) {
window.googleAnalytics = true;
// ga code here ...
}
更好的替代方式是:
当我在网站上添加Google Analytics时,我写了一个名为google-analytics.js的小js文件,这里是内容:
function GoogleAnalytics(accountId, productionServerUrl) {
var _gaq = window._gaq = window._gaq || [];
if (window.googleAnalytics) {
throw new Error("GoogleAnalytics tools already created!");
}
window.googleAnalytics = this;
this.accountId = accountId;
this.dummy = (window.location.hostname != productionServerUrl);
// Work's only on production server and ignore sandboxes
if (this.dummy) {
return ;
}
_gaq.push(['_setAccount', this.accountId]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.onload = function() {
//console.log("GA Loaded !!!!", this, arguments);
window.googleAnalytics.getTracker();
};
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
}
GoogleAnalytics.prototype.getTracker = function () {
if (this.dummy) {
return null;
}
if (undefined == this.pageTracker) {
if (window._gat == undefined) {
console.error("! Google Analytics script is not loaded !");
return null;
}
this.pageTracker = window._gat._getTracker(this.accountId);
}
return this.pageTracker;
}
GoogleAnalytics.prototype.track = function () {
if (this.dummy) {
console.log(" >> GoogleAnalytics.track()", window.location.href, this, arguments);
}
if (this.dummy) {
return ;
}
var tracker = this.getTracker();
if (null == tracker) {
return;
}
tracker._trackPageview();
}
if (undefined == window.googleAnalytics) {
window.googleAnalytics = new GoogleAnalytics('UA-XXXXXXXX-X', 'yoursite.ru');
}
必须在加载jQuery.js后加载此脚本。 在构造函数的参数中插入您的GA-ID和站点URL。 在AJAX页面加载和URL更改后,您可以调用window.googleAnalytics.track()。 祝你好运!