How do I dynamically load Google Analytics JavaScript?

23,323

Solution 1

You could use this snippet from HTML5 Boilerplate.

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
  var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
  (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
  g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
  s.parentNode.insertBefore(g,s)}(document,'script'));
</script>

Solution 2

Try using the exact JavaScript code provided by Google and then conditionally display that section of code based on a construct in your UI framework. You didn't say what platform this is running on, if it's ASP.NET you could put the code in a PlaceHolder or UserControl and then set Visible to true or false based on a config file setting if the script should be included. I've used this approach on multiple sites to prevent the Analytics script from being included in pre-production environments.

Share:
23,323
Admin
Author by

Admin

Updated on February 27, 2020

Comments

  • Admin
    Admin about 4 years

    Without using any other JS frameworks (dojo, jquery, etc), how would I dynamically load Google Analytic's javascript to be used on a web page for web-tracking?

    The typical appropriate to dynamically loading JS is to do the following:

    var gaJs = document.createElement("script");
    gaJs.type = "text/javascript";
    gaJs.src = "http://www.google-analytics.com/ga.js";
    document.body.appendChild(gaJs);
    var pageTracker = _gat._getTracker("UA-XXXXXXXXX");
    pageTracker._initData();
    pageTracker._trackPageview();
    

    But that doesn't work.

    The ga.js file isn't loaded in time for _gat._getTracker & _initData/TrackPageview to function.

    Any ideas on how to properly dynamically load ga.js.

    UPDATE: Seems like someone has attempted to address this problem at the following link. However, it's for use with the old Urchin code and not Google Analytics.

    Any ideas on how to get this to work with ga.js instead of urchin.js?

    http://20y.hu/20070805/loading-google-analytics-dynamically-on-document-load.html

  • Admin
    Admin about 15 years
    @voyager - the first link is showing how to do it using the method I show in my post, which does not work. The second link describes adding the JS to the html HEAD attribute, which is UNdesirable since that will block html rendering.
  • reconbot
    reconbot about 11 years
    you can stick this in a function but remember that _gaq has to be a global (on the window object)