1

I am running another script on my website called "mylivechat" and wanting to track one of the divs in the mylivechat popunder.

However, the mylivechat script seems to take too long load and doesnt get tracked by the google analytics.

Here's the code I use to track the div from the mylivechat app:

<script type="text/javascript" async defer data-cfasync="false" src="https://mylivechat.com/chatinline.aspx?hccid=68268000"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>          

<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-xxxxxx-1', 'auto');
    ga('send', 'pageview');

        ga(function(tracker) {
          //console.log(tracker.get('clientId'));
          var CID = tracker.get('clientId');

          var myl = document.querySelector('div.mylivechat_collapsed');
          myl.addEventListener('click', function() {
             console.log('CLICK:',CID);
             ga('send', 'event', 'contact', 'livechat' , CID);
          });
        });

</script>

If I put the ga tracker function inside a window.onload function, I can get it to work, like the following - it waits to load the scripts first.

<script type="text/javascript" async defer data-cfasync="false" src="https://mylivechat.com/chatinline.aspx?hccid=68268000"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>          

<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-xxxxxxx-1', 'auto');
    ga('send', 'pageview');

    window.onload = function () { 
        ga(function(tracker) {
          //console.log(tracker.get('clientId'));
          var CID = tracker.get('clientId');

          var myl = document.querySelector('div.mylivechat_collapsed');
          myl.addEventListener('click', function() {
             console.log('CLICK:',CID);
             ga('send', 'event', 'contact', 'livechat' , CID);
          });
        });
    }



</script>

However, I'm wondering what are the implications of this? Will it work in most browsers? Is there a better way?

Ke.
  • 2,484
  • 8
  • 40
  • 78

0 Answers0