I'm using both gtag as well as GTM; how do I correctly include both of them in the ? Also, I was wondering if I should be overriding the dataLayer variable or checking if it already exists on every page -- i.e. dataLayer = [];
or window.dataLayer = window.dataLayer || [];
?
Does this look correct?
<!-- Google Tag Manager -->
<script>
window.dataLayer = window.dataLayer || [];
</script>
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UAXXXX"></script>
<script>
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXX');
</script>
This fully answers your concern: https://support.google.com/tagmanager/answer/7582054?hl=en
In short: remove your gtag completely and have all your tracking logic within GTM.
A tag manager is meant to house all your analytics logic and be the single point of access to anything behavioral tracking-related.
Regarding your DL question,
window.dataLayer = window.dataLayer || [];
is more adequate. Never redefine/overwrite the DL. Even when you believe it's not there. Async can be vicious, so be safe is always good in this case.
Oh, also GTM provides dataLayer automatically, so if you're moving your logic to it, you can as well skip defining it to leave the source cleaner. Or you can define it on the template level in case you want to be able to push into it before GTM is loaded.