简体   繁体   English

是否可以将 Google Analytics 代码放在外部 JS 文件中?

[英]Is it possible to put Google Analytics code in an external JS file?

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

try 
{
    var pageTracker = _gat._getTracker("UA-XXXXXXX-1");
    pageTracker._trackPageview();
}
catch(err) {}

Would it be possible to call this script from an external JS file?是否可以从外部 JS 文件调用此脚本? I wanted to to something like:我想这样做:

<script type="text/javascript" src="googleanalytics.js" ></script>

and put one of these on each of my HTML pages.并将其中一个放在我的每个 HTML 页面上。
The code I have above will be inside googleanalytics.js我上面的代码将在 googleanalytics.js 中
Google's instructions was to put the code in each page.谷歌的指示是将代码放在每一页中。 The problem with that is it makes it harder to change the tracking code.这样做的问题是更改跟踪代码变得更加困难。 (We use different tracking codes for our DEV and PROD pages). (我们对 DEV 和 PROD 页面使用不同的跟踪代码)。
I've tried it out and it doesn't seem to be working.我已经尝试过了,它似乎不起作用。
Is there something wrong with doing that?这样做有什么问题吗? Or is there something else causing the problem?还是有其他原因导致问题?

Important FYI Please note that we are using IE6 and 8 browsers (yes, I know, no need to tell me)重要仅供参考请注意我们使用的是 IE6 和 8 浏览器(是的,我知道,无需告诉我)

Yes this is possible. 是的,这是可能的。 If it is not working then there is something else going on. 如果它不起作用,那么还有其他事情发生。

Just a thought, Google Analytics is usually about a day behind in reporting so when you make changes it will take some time before you know it is working. 只是一个想法,谷歌分析通常在报告方面落后一天,因此当您进行更改时,您需要一些时间才能知道它正在运行。 What I like to do is hit a page that does not get traffic very often to assure me that I have my tracking set up correctly. 我喜欢做的是点击一个不经常流量的页面,以向我保证我的跟踪设置正确。

Also, you might try making the link an absolute link in your <script tag. 此外,您可以尝试将链接作为<script标记中的绝对链接。 It might just be looking in the wrong place for the analytics code. 它可能只是在寻找分析代码的错误位置。

Can you not use your server-side language to output the code at the bottom of each page? 你能否使用服务器端语言输出每页底部的代码? Have a function such as output_ga() and call that. 有一个诸如output_ga()之类的函数并调用它。 That way you can change it in one place. 这样你就可以在一个地方改变它。

I came across this post while trying to resolve a similiar issue. 我在尝试解决类似问题时遇到了这篇文章。 After searching further I came across another post that worked for me: 在进一步搜索之后,我遇到了另一篇对我有用的帖子:

Using Google Analytics asynchronous code from external JS file 使用来自外部JS文件的Google Analytics异步代码

I had to move the var _gaq outside of the function it was in so that it became global. 我不得不将var _gaq移到它所在的函数之外,以便它变成全局的。

Hope this helps! 希望这可以帮助!

如果您将脚本划分为2个脚本,就像Google Analytics将传统脚本划分为2个脚本标记一样。

i got an easy way to do this... Since analytic js is asynchronous it won't give any problem... 我有一个简单的方法来做到这一点......由于解析js是异步的,它不会给出任何问题......

include below code in any js file (Please Note: The code i used is new analytics code provided by google analytics) 在任何js文件中包含以下代码(请注意:我使用的代码是谷歌分析提供的新分析代码)

 var imported = document.createElement('script'); imported.src = 'https://www.googletagmanager.com/gtag/js?id=UA-12xxxxxxx-1'; document.head.appendChild(imported); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-12xxxxxxx-1'); 

将谷歌代码包装成功能并在每个页面上执行;)

@Nikko @Nikko

One possible reason is because the GA account was created using the old analytics. 一个可能的原因是因为GA帐户是使用旧分析创建的。 So you must use the traditional analytics code ga.js (_gaq.push). 因此,您必须使用传统的分析代码ga.js(_gaq.push)。 I found an incompatibility in using the new analytics.js with the traditional GA account in the GA website. 我发现使用新的analytics.js与GA网站中的传统GA帐户不兼容。 The hits won't appear so I was forced to use the traditional ga.js. 点击不会出现所以我被迫使用传统的ga.js.

Also, you may set a callback function to assure the hits are successfully sent, like below: 此外,您可以设置回调函数以确保成功发送命中,如下所示:

//traditional way
_gaq.push(['_set', 'hitCallback', function() {
  console.log("%c ga.js finished sending pageview data to analytics %s ", "color:black; background: pink", pageviewUrl);
}]);

//new analytics way
ga('send', 'pageview', {
            'page': pageviewUrl,
            'hitCallback': function() {
                console.log("%c analytics.js done sending data. pageview url = %s ", "color: black, background: pink", pageviewUrl);
            }
        });

where pageviewUrl = the url of the site 其中pageviewUrl =网站的网址

Hope that helps! 希望有所帮助!

Upload google analytics dynamically: 动态上传谷歌分析:

function loadGoogleAnalytics(){
    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; 
    ga.async = true;
    ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-XX';

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
}

loadGoogleAnalytics(); //Create the script  

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-XXXXXX-XX');

Don't forget to replace XXXXXX-XX with your account id. 不要忘记将XXXXXX-XX替换为您的帐户ID。

 (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX-X'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX-X');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM