Getting Started with Google Analytics

First of all I assume you know why you are interested in Google Analytics Service.

Usage Guide:

Adding analytics.js to Your Site

The analytics.js library is a JavaScript library for measuring how users interact with your website. This document explains how to add analytics.js to your site.

 

Now put the following js code snippet in the <head> section of your pages.

In Rails; keep this snipped in your `layouts/application.html.erb`

<!-- Google Analytics -->

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

<!-- End Google Analytics -->

The above code does four main things:

  1. Creates a element that starts asynchronously downloading the analytics.js JavaScript library from https://www.google-analytics.com/analytics.js
  2. Initializes a global ga function (called the ga() command queue) that allows you to schedule commands to be run once the analytics.js library is loaded and ready to go.
  3. Adds a command to the ga() command queue to create a new tracker object for the property specified via the'UA-XXXXX-Y' parameter.
  4. Adds another command to the ga() command queue to send a pageview to Google Analytics for the current page.

For modern browsers

This will use the feature of modern browsers to preload the assets



window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

 async src='https://www.google-analytics.com/analytics.js'>
<!-- End Google Analytics -->

For more info see 

Find your tracking code, tracking ID, and property number

 

Sources:

https://developers.google.com/analytics/devguides/collection/analyticsjs/#the_javascript_tracking_snippet

https://support.google.com/analytics/answer/1032385

https://developers.google.com/api-client-library/ruby/apis/analytics/v3#installing-the-google-api-client-gem

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s