How do I dynamically load Google Analytics JavaScript?

前端 未结 5 2175
[愿得一人]
[愿得一人] 2020-12-02 21:29

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 w

相关标签:
5条回答
  • 2020-12-02 21:48
    function loadGA()
    {
        if(typeof _gat == 'function') //already loaded
        {
            //innitGA();
            // you may want the above line uncommented.. 
            // I'm presuming that if the _gat object is there
            // you wouldn't want to.
            return;
        }
        var hostname = 'google-analytics.com';
        var protocol = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
        js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', protocol+hostname+'/ga.js');
        document.body.appendChild(js);
        //2 methods to detect the load of ga.js
        //some browsers use both, however
        loaded = false; // so use a boolean
        js.onreadystatechange = function () {
            if (js.readyState == 'loaded') 
            { 
                if(!loaded)
                {
                    innitGA();
                }
                loaded = true;
            }
        };
        js.onload = function () 
        {
            if(!loaded)
            {           
                innitGA();
            }
            loaded = true;
        };
    }
    
    function innitGA()
    {
        //var pageTracker = _gat._getTracker('GA_ACCOUNT/PROFILE_ID');
        //pageTracker._initData();
        //pageTracker._trackPageview();
        alert('oh hai I can watch plz?');
    }
    

    just call loadGA()... tested on IE6/7/8, FF3, Chrome and Opera

    sorry if I'm a bit late to this party.

    0 讨论(0)
  • 2020-12-02 21:54

    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.

    0 讨论(0)
  • 2020-12-02 21:56

    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>
    
    0 讨论(0)
  • 2020-12-02 22:03

    I've literally just put something together that does this... using jquery. The trick is to add a load event to the script tag with the tracking code in it.

    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    var gaScript = document.createElement('script');
    var loaded = false;
    gaScript.src = gaJsHost + "google-analytics.com/ga.js";
    
    $(gaScript).load(function(){
      loaded = true;
      var pageTracker = _gat._getTracker(Consts.google_analytics_uacct);
      pageTracker._initData();
      pageTracker._trackPageview();
    });
    
    document.body.appendChild(gaScript);
    
    // And to make it work in ie7 & 8
    gaInterval = setInterval(function() {
      if (!loaded && typeof _gat != 'undefined') {
        $(gaScript).load();
        clearInterval(gaInterval);
      }
    },50);
    

    The thing i'm trying to work out is... is this allowed by google.

    0 讨论(0)
  • 2020-12-02 22:05

    Server side programming would be easier I guess, but I found this some time ago. Notice that it specifically sets it to the html head.

    Also check on the first link down on 'Adding Javascript Through Ajax'.

    0 讨论(0)
提交回复
热议问题