Skip to content
Advertisement

Include google analytics in external JS file

I would like to know how I can take the Google Analytics Code below and add it to an external JS file that all the pages are accessing.

The code that is in all my html files now:

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

  gtag('config', 'XXXXXXXXXX');
</script> 

How I want it to be:

HTML:

<head>
<script src="/js/google.js"></script>
</head>

google.js:

##Some code that does the same as the code the above. I tried adding the exact snippet, but I don't think it works because of the <script> tags, and I don't know how to remove them since one has an "SRC" attribute.

Any help would be appreciated, as I cannot find answers for this elsewhere on the web.

Advertisement

Answer

Try adding this to your /js/google.js file:

let ga_id = "XXXXXXXX";
let ga_script = document.createElement('SCRIPT');

ga_script.type = 'text/javascript';
ga_script.src = `https://www.googletagmanager.com/gtag/js?id=${ga_id}`;
let script2 = document.createElement('SCRIPT');

script2.type = 'text/javascript';

script2.text = `
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '${ga_id}');`;
  
  document.body.appendChild(ga_script)
  document.body.appendChild(script2)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement