Ernanni
Ernanni

Reputation: 53

Google Analytics tagging

I have the current code to track the % of a scroll on a page.

ga('create', 'UA-68653010-1', 'auto');
window.onbeforeunload = function(){
  var viewportHeight = $(this).height();
  var progress = $(this).scrollTop() / ($(document).height() - viewportHeight);
  ga('send', 'event', 'scroll', Math.round(progress*100));
};

But whenever the event should send the hit it returns a different than the expected, which one of the Parameters is:

exd:ReferenceError: ga is not defined

Upvotes: 2

Views: 92

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Include your JS-files (fragments) in the right sequence.

Include this script first:

<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-68653010-1', 'auto') ; 
</script>

... Then include your main JS-file which contains onbeforeunload handler:

    window.onbeforeunload = function(){
      var viewportHeight = $(this).height();
      var progress = $(this).scrollTop() / ($(document).height() - viewportHeight);
      ga('send', 'event', 'scroll', Math.round(progress*100));
};

Upvotes: 2

Related Questions