For years I have had the Google Universal Analytics snippet in an external js file. It of course had to be converted to use it there. I am now trying to do the same thing with the newer Google Analytics 4 (gtag) snippet. So far, the data collection in Google Analytics is not happening. I DID test the snippet in the header first, and it works that way.
Here is the snippet as provided by Google, which is supposed to go in your head section:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=myGtagID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'myGtagID');
</script>
Here is the call that is already in each web page in their head section:
<script type="text/javascript">
<!--
window.onload=function(){
analytics();
}
//-->
</script>
Here is the code inside my external js file.:
function analytics(){
/* Universal Analytics property (analytics.js) - OLD CODE WHICH WORKS */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'myUA_ID']);
_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);
})();
/* Google Analytics 4 property (gtag.js) - NEW CODE NOT WORKING */
gtag.push(['js', new Date()]);
gtag.push(['config', 'myGtagID']);
(function() {
var ga4 = document.createElement('script'); ga4.type = 'text/javascript'; ga4.async = true;
ga4.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.googletagmanager.com/gtag/js?id=myGtagID';
var t = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga4, t);
})();
}
GA4 currently doesn't work with the file:// protocol, only http:// and https://
Are you using file:// protocol in Cordova, for example? If so, GA4 will block analytics.
I just took another look at your code. It appears you are attempting to use GA4 just like you used GA3. The 2 are not interoperable and don't share the same methods and properties. GA4 is a completely new analytics product from Google.
Please refer to the documentation from Google for more details.