1

I have a Enterprise Trading site. I have included the Google analytic's code in every jsp of my site. Now the problem is since in my site some pages are included within other pages not using frames just by ajax call and changing the div contents. As a result the when a new page is loaded within the same page Google Analytic's wont be called since the entire page is not loaded, and the browser considers only page load to load the js, Not frame change. Can any one suggest a solution for this

4

1 回答 1

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()。祝你好运!

于 2013-06-13T05:55:20.353 回答