Using Google Analytics asynchronous code from external JS file

妖精的绣舞 提交于 2019-11-26 16:05:47

问题


I'm trying to add the asynchronous version of the Google Analytics tracking code to a website.

I'd like to keep the JavaScript in a separate file, and call it from there.

Here's what I've currently got in my .js file:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function loadtracking() {
    var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
        _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';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
}

addLoadEvent(loadtracking);

And here's what I've got in the <head> tag of my Master page:

<script type="text/javascript" src="js/google-analytics.js" ></script>

However, there's obviously a problem as after a few days, I'm not getting stats through!

Any ideas what I need to change?

Thanks, Neil


EDIT: Ok... After some feedback below, I'm going to add the new current contents of my .js file. I'll keep it updated so that if/when this gets solved, it will hopefully help other people trying to do similar things.

var _gaq = _gaq || [];

function loadtracking() {
        window._gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
        window._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';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
}

loadtracking();

回答1:


Your variable definition var _gaq is inside a function. That means it's locally scoped inside that function and won't exist globally. Google Analytics depends on the global variable _gaq. If you want to keep it inside a function like that, reference it as window._gaq.




回答2:


You completely miss the point of the asynchronous tracking code. Don't put it in an external file because that's exactly like including the old synchronous GA.

And most importantly don't defer the tracking code to window.onload as it may fire too late.

If you use the asynchronous GA just put it in the top of you document in an inline script tag. This is the recommendation on Google Analytics website as well.

Insert the asynchronous snippet at the bottom of the <head> section of your pages, after any other scripts your page or template might use.




回答3:


Honestly I have not read through all these posts since they are rather old. However I recently had the need to add Gtag (google tag manager for analytics tracking) to an old website that was a 1000 static HTML files and (LUCKILY) a the html files had a single include js file for the spry menu bar, like i said very old site! For my purposes I wasn't worried about performance but measuring the traffic so we can migrate it. your case may be different but the below code will work for external js includes of Gtag.

I used this file to load the code below since the above code is for legacy ga.js

//Added Google Anyltics Tag Container Tracking - included here to min rebuilding DOM 

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

    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-XXXXXXXXX-1');
//Confirmed with Google tag Assistant


来源:https://stackoverflow.com/questions/3263818/using-google-analytics-asynchronous-code-from-external-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!