Ad

Dynamically Add Google Analytics

- 1 answer

The users of my website needs to give their consent before I can use Google Analytics. Therefor I have to dynamically add the script. But I can't seem to get it to work.

I tried the approaches from this question: Dynamically add script tag with src that may include document.write

Which indeed added the script tag, but Analytics doesn't fire off events and pageviews.

If I add this snippet to my index.html, everything works fine.

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-MYGOOGLEID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
</script>

Any ideas?

This is how I try to add it.

const s = document.createElement('script');
s.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=UA-MYGOOGLEID');
s.async = true;
document.head.appendChild(s);

window.dataLayer = window.dataLayer || [];
window.gtag = () => {dataLayer.push(arguments);}

window.gtag('js', new Date());
window.gtag('config', 'UA-MYGOOGLEID');
Ad

Answer

arguments doesn't exist in a fat arrow function.

The solution was to leave it as a ES5 function.

window.gtag = function() {
  window.dataLayer.push(arguments);
};

Tests

function gtagtest() {console.log(arguments)}
  gtagtest('event', 'testEvent', {
   'event_category': 'testClick'
  })
Arguments(3) ["event", "testEvent", {…}, callee: ƒ, Symbol(Symbol.iterator): ƒ]

const gtagtest2 = (...args) =>  {console.log(args)}
gtagtest2('event', 'testEvent', {
  'event_category': 'testClick'
})
(3) ["event", "testEvent", {…}]

const gtagtest3 = () =>  {console.log(arguments)}
gtagtest3('event', 'testEvent', {
  'event_category': 'testClick'
})
Uncaught ReferenceError: arguments is not defined
at gtagtest3 (<anonymous>:1:39)
at <anonymous>:1:1
Ad
source: stackoverflow.com
Ad