How do I dynamically load Google Analytics JavaScript?

前端 未结 5 2231
[愿得一人]
[愿得一人] 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 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.

提交回复
热议问题