如何动态加载 Google Analytics JavaScript?

发布于 2024-07-16 12:10:38 字数 974 浏览 7 评论 0原文

使用任何其他 JS 框架(dojo、jquery 等),如何动态加载 Google Analytic 的 javascript 以在网页上用于网络跟踪?

动态加载 JS 的适当方法是执行以下操作:

var gaJs = document.createElement("script");
gaJs.type = "text/javascript";
gaJs.src = "http://www.google-analytics.com/ga.js";
document.body.appendChild(gaJs);
var pageTracker = _gat._getTracker("UA-XXXXXXXXX");
pageTracker._initData();
pageTracker._trackPageview();

但这不起作用。

ga.js 文件未及时加载 _gat._getTracker & 。 _initData/TrackPageview 正常运行。

关于如何正确动态加载 ga.js 的任何想法。

更新:似乎有人尝试通过以下链接解决此问题。 但是,它适用于旧的 Urchin 代码,而不是 Google Analytics。

关于如何让它与 ga.js 而不是 urchin.js 一起工作有什么想法吗?

http://20y.hu/20070805/loading-google -analytics-dynamically-on-document-load.html

Without using any other JS frameworks (dojo, jquery, etc), how would I dynamically load Google Analytic's javascript to be used on a web page for web-tracking?

The typical appropriate to dynamically loading JS is to do the following:

var gaJs = document.createElement("script");
gaJs.type = "text/javascript";
gaJs.src = "http://www.google-analytics.com/ga.js";
document.body.appendChild(gaJs);
var pageTracker = _gat._getTracker("UA-XXXXXXXXX");
pageTracker._initData();
pageTracker._trackPageview();

But that doesn't work.

The ga.js file isn't loaded in time for _gat._getTracker & _initData/TrackPageview to function.

Any ideas on how to properly dynamically load ga.js.

UPDATE: Seems like someone has attempted to address this problem at the following link. However, it's for use with the old Urchin code and not Google Analytics.

Any ideas on how to get this to work with ga.js instead of urchin.js?

http://20y.hu/20070805/loading-google-analytics-dynamically-on-document-load.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

画离情绘悲伤 2024-07-23 12:10:38

您可以使用 HTML5 Boilerplate 中的这段代码。

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
  var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
  (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
  g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
  s.parentNode.insertBefore(g,s)}(document,'script'));
</script>

You could use this snippet from HTML5 Boilerplate.

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
  var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
  (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
  g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
  s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
三五鸿雁 2024-07-23 12:10:38

我想服务器端编程会更容易,但我发现 这个 不久前。 请注意,它专门将其设置为 html head

另请检查“通过 Ajax 添加 Javascript”中的第一个链接。

Server side programming would be easier I guess, but I found this some time ago. Notice that it specifically sets it to the html head.

Also check on the first link down on 'Adding Javascript Through Ajax'.

允世 2024-07-23 12:10:38

尝试使用 Google 提供的确切 JavaScript 代码,然后根据 UI 框架中的构造有条件地显示该代码部分。 您没有说明它在哪个平台上运行,如果是 ASP.NET,您可以将代码放在 PlaceHolder 或 UserControl 中,然后根据配置文件设置将 Visible 设置为 true 或 false(如果应包含脚本)。 我已在多个站点上使用此方法来防止分析脚本包含在预生产环境中。

Try using the exact JavaScript code provided by Google and then conditionally display that section of code based on a construct in your UI framework. You didn't say what platform this is running on, if it's ASP.NET you could put the code in a PlaceHolder or UserControl and then set Visible to true or false based on a config file setting if the script should be included. I've used this approach on multiple sites to prevent the Analytics script from being included in pre-production environments.

心欲静而疯不止 2024-07-23 12:10:38
function loadGA()
{
    if(typeof _gat == 'function') //already loaded
    {
        //innitGA();
        // you may want the above line uncommented.. 
        // I'm presuming that if the _gat object is there
        // you wouldn't want to.
        return;
    }
    var hostname = 'google-analytics.com';
    var protocol = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', protocol+hostname+'/ga.js');
    document.body.appendChild(js);
    //2 methods to detect the load of ga.js
    //some browsers use both, however
    loaded = false; // so use a boolean
    js.onreadystatechange = function () {
        if (js.readyState == 'loaded') 
        { 
            if(!loaded)
            {
                innitGA();
            }
            loaded = true;
        }
    };
    js.onload = function () 
    {
        if(!loaded)
        {           
            innitGA();
        }
        loaded = true;
    };
}

function innitGA()
{
    //var pageTracker = _gat._getTracker('GA_ACCOUNT/PROFILE_ID');
    //pageTracker._initData();
    //pageTracker._trackPageview();
    alert('oh hai I can watch plz?');
}

只需调用 loadGA()... 在 IE6/7/8、FF3、Chrome 和 Opera 上进行测试,

如果我来晚了一点,抱歉。

function loadGA()
{
    if(typeof _gat == 'function') //already loaded
    {
        //innitGA();
        // you may want the above line uncommented.. 
        // I'm presuming that if the _gat object is there
        // you wouldn't want to.
        return;
    }
    var hostname = 'google-analytics.com';
    var protocol = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', protocol+hostname+'/ga.js');
    document.body.appendChild(js);
    //2 methods to detect the load of ga.js
    //some browsers use both, however
    loaded = false; // so use a boolean
    js.onreadystatechange = function () {
        if (js.readyState == 'loaded') 
        { 
            if(!loaded)
            {
                innitGA();
            }
            loaded = true;
        }
    };
    js.onload = function () 
    {
        if(!loaded)
        {           
            innitGA();
        }
        loaded = true;
    };
}

function innitGA()
{
    //var pageTracker = _gat._getTracker('GA_ACCOUNT/PROFILE_ID');
    //pageTracker._initData();
    //pageTracker._trackPageview();
    alert('oh hai I can watch plz?');
}

just call loadGA()... tested on IE6/7/8, FF3, Chrome and Opera

sorry if I'm a bit late to this party.

柠栀 2024-07-23 12:10:38

我实际上只是使用 jquery 将一些东西放在一起来执行此操作。 诀窍是将加载事件添加到其中包含跟踪代码的脚本标记。

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
var gaScript = document.createElement('script');
var loaded = false;
gaScript.src = gaJsHost + "google-analytics.com/ga.js";

$(gaScript).load(function(){
  loaded = true;
  var pageTracker = _gat._getTracker(Consts.google_analytics_uacct);
  pageTracker._initData();
  pageTracker._trackPageview();
});

document.body.appendChild(gaScript);

// And to make it work in ie7 & 8
gaInterval = setInterval(function() {
  if (!loaded && typeof _gat != 'undefined') {
    $(gaScript).load();
    clearInterval(gaInterval);
  }
},50);

我想要解决的问题是......谷歌是否允许这样做。

I've literally just put something together that does this... using jquery. The trick is to add a load event to the script tag with the tracking code in it.

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
var gaScript = document.createElement('script');
var loaded = false;
gaScript.src = gaJsHost + "google-analytics.com/ga.js";

$(gaScript).load(function(){
  loaded = true;
  var pageTracker = _gat._getTracker(Consts.google_analytics_uacct);
  pageTracker._initData();
  pageTracker._trackPageview();
});

document.body.appendChild(gaScript);

// And to make it work in ie7 & 8
gaInterval = setInterval(function() {
  if (!loaded && typeof _gat != 'undefined') {
    $(gaScript).load();
    clearInterval(gaInterval);
  }
},50);

The thing i'm trying to work out is... is this allowed by google.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文