var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");
document.write(unescape(\"%3Cscript src=\'\" + gaJsHost + \"google-anal
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.
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
I had to move the var _gaq outside of the function it was in so that it became global.
Hope this helps!
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. It might just be looking in the wrong place for the analytics code.
@Nikko
One possible reason is because the GA account was created using the old analytics. So you must use the traditional analytics code ga.js (_gaq.push). I found an incompatibility in using the new analytics.js with the traditional GA account in the GA website. The hits won't appear so I was forced to use the traditional 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
Hope that helps!
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. That way you can change it in one place.
Wrap google code into function and execute on each page ;)