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:

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:

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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With