Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading google analytics parametrized async page tracking script

If I use the google analytics async site tracking script, in the end of head section of my page, everything works as expected:

<head>   
    <script type="text/javascript">

        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-XXXXX-X']);
        _gaq.push(['_setDomainName', 'test.com']);
        _gaq.push(['_trackPageview', '/title=ied&action=fire']);

        (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);
        })();

    </script>
</head>

In the fiddler there can be seen 2 requests:

enter image description here enter image description here

For some reason I need the script to be parametrized, so I wrap it within custom googleAnalytics function which gets 2 parameters:

function googleAnalytics(domain, queryString) {
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_setDomainName', domain]);
    _gaq.push(['_trackPageview', queryString]);

    (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);
    })();
}

Abowe code has been saved to GoogleAnalytics.js file. I loaded it to the page in the head section like below:

<head>
    <script src="/script/GoogleAnalytics.js" type="text/javascript" language="javascript"></script>
    <script type="text/javascript">googleAnalytics('test.com', '/title=ied&action=fire');</script>
</head>

But this time fiddler shows only 1 request:

enter image description here

The Google Analytics Tracking Code Debugger also shows nothing. Only ga.js script is downloaded but there is no other request which populates data for google analytics report. What is wrong in this approach and how it can be fixed ?

Btw: I need this 2 parameters and the async version of the tracking script.

Regards

like image 481
jwaliszko Avatar asked May 10 '26 05:05

jwaliszko


1 Answers

Your problem is that the your _gaq declaration is local in scope. ga.js loads, and looks for _gaq in the global scope. (Once the script is injected, it no longer has access to the function's scope.)

To fix it, you can either place var _gaq = _gaq || []; outside of the function, or you can replace it within the function with this:

window._gaq = window._gaq || []; 

This will resolve your problem.

like image 189
Yahel Avatar answered May 11 '26 18:05

Yahel