0

I am trying to update my google analytics property. In the past I put the code in an existing javascript library. I don't see how to do that with the new gtag.js

old code include in an existing javascript file

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-29861433-1', 'garyjohnsoninfo.info');
ga('send', 'pageview');

this fails when put in an existing javascript file

<script async src="https://www.googletagmanager.com/gtag/js?id=G-0E6CK94QYH"></script>

This is the gtag.js

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-0E6CK94QYH"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-0E6CK94QYH');
</script>
gmgj
  • 71
  • 1
  • 4
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 21 '23 at 19:06
  • This is a duplicate of this: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file There's nothing special about gtag.js. It's a quesion about loading a js file via js. Voting to close as a duplicate. – BNazaruk May 23 '23 at 21:26

1 Answers1

0

I found that this code worked for my (with help from ChatGPT!)

 $(document).ready( function(){
  // Create the script element for Google Tag Manager
  var gtmScript = document.createElement('script');
  gtmScript.src = "https://www.googletagmanager.com/gtag/js?id=yourID";
  gtmScript.async = true;

  // Create the script element for configuring Google Analytics
  var gaScript = document.createElement('script');
  gaScript.textContent = `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'yourID');
  `;

  // Append the scripts to the head of the document
  document.head.appendChild(gtmScript);
  document.head.appendChild(gaScript);
});