Skip to content

Instantly share code, notes, and snippets.

@dipaktelangre
Last active December 19, 2015 13:58
Show Gist options
  • Select an option

  • Save dipaktelangre/5965447 to your computer and use it in GitHub Desktop.

Select an option

Save dipaktelangre/5965447 to your computer and use it in GitHub Desktop.
Notes for Demo session on Google Analytics
/*Google Analytics?
Google Analytics is a service offered by Google that generates detailed statistics about a website's traffic and traffic sources and measures conversions and sales.
Google Analytics can track visitors from all referrers, including search engines and social networks, direct visits and referring sites. It also displays advertising, pay-per-click networks, email marketing and digital collateral such as links within PDF documents.
How it work ?
Page tags-->
Google Analytics is implemented with "page tags". A page tag, in this case called the Google Analytics Tracking Code is a snippet of JavaScript code that the website owner user adds to every page of the website. The tracking code code runs in the client browser when the client browses the page (if JavaScript is enabled in the browser) and collects visitor data and sends it to a Google data collection server as part of a request for a web beacon.
First party cookie -->
Cookie creted by the client side subdomain.
The tracking code sets first party cookies (If cookies are enabled in the browser) on each visitor's computer. These cookies store anonymous information such as whether the visitor has been to the site before (new or returning visitor), the timestamp of the current visit, and the referrer site or campaign that directed the visitor to the page (e.g. search engine, keywords, banner or email).
Start with Google Analytics-->
1) Create google account or login with gmail in analytics.
2) Create new analtics account.
3) Copy tracking code and paste it on every page that you want to track.
Take look at code --> */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-41489172-3']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//The snippet above represents the minimum configuration needed to track a page asynchronously. It uses _setAccount to set the page's web property ID and then calls _trackPageview to send the tracking data back to the Google Analytics servers.
Ready to Go !!!
Test Tracking --->
I highly recommend to use chrome degubber to debug javascript
1) Check ga.js is is loaded or not. Open network tab in chrome debugger where you can see all the requested url and their progress.
2) Add some important chrome extensions
Google analytics Debugger --> Debugger for google analytics
jquerify --> Embbed jquiry to the page
How the Asynchronous Syntax Works ?
_gaq object is a queue data structure. It collect API call untill ga.js ready to execute them.
To add use _gaq.push() method.
Tracking with HTML Event Handlers -->
<button onclick="_gaq.push(['_trackEvent', 'button3', 'clicked'])"/> Click Me ??</button>
One Push, Multiple Commands -->
_gaq.push(
['_setAccount', 'UA-41489172-3'],
['_setDomainName', 'example.com'],
['_setCustomVar', 1, 'Section', 'Life & Style', 3],
['_trackPageview']
);
Avoiding Common Pitfalls -->
- Method names are case-sensitive
- Use the correct method names.
- Only strings should be passed in with quotes
- Make sure that strings do not contain leading or trailing whitespace
Disabling Tracking -->
To disable tracking, set the following window property to true:
window['ga-disable-UA-41489172-3'] = true;
/************************************************************************************************************/
Custom Variables - Web Tracking (ga.js) --->
Custom variables are name-value pair tags that you can insert in your tracking code in order to refine Google Analytics tracking.
Scope -->
1) visitor --> Client visit the page. i.e Browser
2) Session --> Active duration of visitor
3) Page --> Activity of user i.e pageview, event
Page leve custome variable -->
Use page-level custom variables to define a collection of page-level activities by your users.
ex. Find wich sction of nespaper site is popular these days
_gaq.push(['_setCustomVar',
1, // This custom var is set to slot #1. Required parameter.
'Section', // The top-level name for your online content categories. Required parameter.
'Life & Style', // Sets the value of "Section" to "Life & Style" for this particular aricle. Required parameter.
3 // Sets the scope to page-level. Optional parameter.
]);
You even can dig out sub section of section
_gaq.push(['_setCustomVar',
2, // This custom var is set to slot #2. Required parameter.
'Sub-Section', // The 2nd-level name for your online content categories. Required parameter.
'Fashion', // Sets the value of "Sub-section" to "Fashion" for this particular article. Required parameter.
3 // Sets the scope to page-level. Optional parameter.
]);
Session-level Custom Variables -->
Use session-level custom variables to distinguish different visitor experiences across sessions. Suppose logged in user vs annonimous user.
_gaq.push(['_setCustomVar',
1, // This custom var is set to slot #1. Required parameter.
'User Type', // The name of the custom variable. Required parameter.
'Member', // Sets the value of "User Type" to "Member" or "Visitor" depending on status. Required parameter.
2 // Sets the scope to session-level. Optional parameter.
]);
If you want to track wich logged in user has purchesed item or anything from your site.... you can ....
_gaq.push(['_setCustomVar',
2, // This custom var is set to slot #2. Required parameter.
'Shopping Attempts', // The name of the custom variable. Required parameter.
'Yes', // The value of the custom variable. Required parameter.
// (you might set this value by default to No)
2 // Sets the scope to session-level. Optional parameter.
]);
Visitor-level Custom Variables --->
Use visitor-level custom variables to distinguish categories of visitors across multiple sessions.
Set this custom variable as a one-time function, since the value would persist across the life of the visitor cookie.
_gaq.push(['_setCustomVar',
1, // This custom var is set to slot #1. Required parameter.
'Member Type', // The name of the custom variable. Required parameter.
'Premium', // The value of the custom variable. Required parameter.
// (possible values might be Free, Bronze, Gold, and Platinum)
1 // Sets the scope to visitor-level. Optional parameter.
]);
***********************************************************************************************************************
Event tracking -->
Use to record user intraction with website element such as Flash driven menu system.
With ga.js we can apply envent tracking to -->
- Flash driven element
- Embeded AJAX page element
- Page gadgets
- File Downloads
- Load time for data
Tips to Usefull Event Tracking -->
- Determine in advance all elements for which you want to track data
- Work with your report user to plan your Event Tracking reports.
- Adopt a consistent and clear naming convention.
------------------------------------------------
Setting Up Event Tracking -- >
1) Set up tracking to site
2) Call to _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
- Catagory of event i.e Video
- Action i.e Play
- opt_label - label for action i.e video name
- opt_value -numebric value to provide extra info about action e.g Video play for 10 sec
- opt_noninteraction - A boolean that when set to true, indicates that the event hit will not be used in bounce-rate calculation.
3) View Report :)
Try this ???? -->
<a href="#" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Someone liks you !!']);">Play</a>
Track total downloads of video:
_gaq.push(['_trackEvent', 'Videos', 'Downloaded', 'Somebody loves you.']);
To find Video Load time:
_gaq.push(['_trackEvent', 'Videos', 'Video Load Time', 'Baby,Baby', 20]);
Bounce Rate Impact -->
In general, a "bounce" is described as a single-page visit to your site. When a user comes to a single page on your website and then exits without causing any other request to the Analytics server for that session.
If opt_noninteraction is set to true means event tracking hit not counted in bounce. So if you miss to set opt_noninteraction then your page bounce rate may be decrease as it counted as a hit to that page.
**************************************************************************************************************************
Ecommerce -->
Send each user order transections to google database.
How to ?
1) Enable ecommerce tracking on the profile settings page for your website.
2) Implement the ga.js ecommerce tracking methods in your shopping cart pages
Implementation -->
1) _addTrans(transactionId, affiliation, total, tax, shipping, city, state, country) -->
Initialize trasection object. It store all information related to single transection such as transection ID, shipping charges, billing address.
Transection ID sholud be same to all the items in single transection.
_gaq.push(['_addTrans',
'1234', // transaction ID - required
'Womens Apparel', // affiliation or store name
'28.28', // total - required; Shown as "Revenue" in the
// Transactions report. Does not include Tax and Shipping.
'1.29', // tax
'15.00', // shipping
'San Jose', // city
'California', // state or province
'USA' // country
]);
2) _addItem(transactionId, sku, name, category, price, quantity) -->
Adds Item to transection with associated inforamtion.
sku (Stock keeping Unit) --> required and should be unique. If duplicated, only last itme will be track.
_gaq.push(['_addItem',
'1234', // transaction ID - necessary to associate item with transaction
'DD44', // SKU/code - required
'T-Shirt', // product name - necessary to associate revenue with product
'Olive Medium', // category or variation
'11.99', // unit price - required
'1' // quantity - required
]);
3) _trackTrans() -->
Submit the transaction to the Analytics servers.
_gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
Local Currencies -->
Specify the local currency of the transaction using the following command, before the call to _trackTrans is performed:
_gaq.push(['_set', ‘currencyCode’, ‘EUR’]);
****************************************************************************************************************************
Finally Embed ga.js with jquery :)
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-41489172-3']);
_gaq.push(['_setDomainName', 'none']);
//_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
$(document).ready(function(){
createButton();
});
$(document).on('click', '#btn', function(){
_gaq.push(['_trackPageview']);
createButton();
});
var handle = setInterval(function(){
$("#btn").trigger('click');
},2000);
// clearInterval(handle);
/*$("#btn").click(function(){
console.log("Hi");
});*/
var count = 0;
function createButton()
{ var button = "<input type='button' id='btn' value='Button - "+count++ +"'>";
$("body").append(button);
}
****************************************************************************************************************************
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment