Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Adding Google Analytics Global Site Tag

Hi everyone,

Now that Google Analytics has moved away from analytics.js to gtag.js, how does one add the tracking script to the dash app ? As previously it looked like:

<script>
(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','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-39373211-1', 'auto');
ga('send', 'pageview');
</script>

and now it with gtag.js it looks like:

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

  gtag('config', 'UA-111343278-1');
</script>

With two scripts in the gtag.js, do I need to use app.scripts.append_script twice ?

Any help would be appreciated. Thanks !

Update
analytics.js still works ! However, a workaround gtag.js would be great too !

1 Like

Hey I’m trying to get basic GA set up on my Dash app. I haven’t been able to find any success so far in getting that to work, js or otherwise. Could you provide a real quick overview of how to add GA to my app? I would be forever grateful :slight_smile:

Hi Stayup,

Kindly refer to my repo:

First you need to create a gtag.js script as in my repo. Then if you refer to app.py at the end of the script, you can see I use

app.scripts.append_script({
‘external_url’: ‘https://cdn.rawgit.com/jasonchanhku/UFC-MMA-Predictor/f6830a25/gtag.js
})

Note that you need to put your gtag.js through rawgit.

Regards,
Jason

1 Like