Google Analytics Javascript Tutorial

Last Updated: September 5, 2023

JavaScript is the most popular programming language in the world.

It is easy to learn (thus widespread adoption), client-side (thus very fast, no server-side processing) and the de facto language of web browsers (thus dubbed as the language of the web).

Why learn JavaScript?

Every analyst needs to have two strong core skills in order to excel in the field of digital analytics. One is statistics and the other is JavaScript.

You need knowledge of statistics in order to interpret the data accurately.

You need to know JavaScript in order to get the data you want to analyse.

Statistics help you with data interpretation and JavaScript help you with data collection.

So if you are good at data interpretation but weak in data collection, you will always have to rely on a third party for your data collection needs.

Unless your data requirements are met, you are stuck. You can’t move forward with your analysis because you don’t have the data to analyze. You can’t assess the quality of data because you don’t understand how the data was collected. You need to work with whatever data you have got. Pretty helpless state.

Conversely, if you are strong in data collection but weak in data interpretation you won’t be able to improve the business bottom line. You have all the data you need but you don’t know how to use and interpret it correctly.

So it won’t be an exaggeration to say that statistics and JavaScript are like the two legs of a web analyst.

You need both legs in order to stand and run in the field of Web Analytics. With just one leg you have got only two options: either hop or use a developer as a crutch all your working life.

Both of these situations are undesirable and avoidable.

That’s why I cover both data interpretation and data collection issues on this blog. I strive to be good in both of these areas and expect you to do the same.

But why JavaScript and not any other programming language?

JavaScript is the most useful programming language for a web analyst.

All the measurement and marketing tags whether it is Google Analytics tracking code, ecommerce tracking code, event tracking code or Google Adwords conversion tracking code are written in JavaScript.

You need a good working knowledge of JavaScript in order to implement:

#1 Ecommerce tracking
#2 Event tracking
#3 Phone Call Tracking
#4 Scroll Tracking
#5 Video Tracking
#6 Social Interactions Tracking
#7 Enhanced ecommerce tracking
#8 Cross domain tracking

and just about any tracking in Google Analytics.

Both analytics.js library and gtag.js library used by Google Analytics are JavaScript files. Without JavaScript, there will be no Google Analytics and Google Tag Manager won’t be useful.

Role of JavaScript in maintaining a web document

where javascript fits

The three most important scripting languages which are widely used to create a web document are: HTML, CSS and JavaScript.

  • HTML (or Hyper Text Markup Language) is used to develop text content of a web document.
  • CSS (or Cascading Stylesheet) is used to control the layout and formatting of the text developed through HTML.
  • JavaScript is used to control the behaviour of HTML and CSS elements, users and web browsers.

These three scripting languages together create the modern web page which we see today.

We need to learn to keep the HTML, CSS and JavaScript code separated as much as possible on a web page by storing them in different files.

What that means is that all CSS code should be stored in a CSS file and all the JavaScript code should be stored in a JavaScript file.

Often web pages contain all of these three different types of codes together and this is where the problem starts. When you mix all of these three different types of codes together it becomes difficult to understand, diagnose, reuse and maintain a piece of code.

Methods to add JavaScript to HTML

There are three methods to add JavaScript code to an HTML document:

  1. Inline JavaScript
  2. Embedded JavaScript
  3. External JavaScript

Inline JavaScript

Inline JavaScript is JavaScript added to an HTML tag. For example, analytics.js code will look like below

<a onClick=”ga(‘send’, ‘social’, ‘Linkedin’,’Share’,window.location.href);“>….</a>

And gtag.js code will look like below

<a onClick=”gtag(‘event’, ‘Social’, {‘event-category’: ‘Social’ ,‘event_action’: ‘LinkedIn Share’, ‘event value’: ‘wnidow.location.href });>….</a>

Here the text in bold is a JavaScript statement. You need an event handler like ‘onClick’ in order to use inline JavaScript.

Embedded JavaScript

Embedded JavaScript is JavaScript added to an HTML document using the <script> tag which doesn’t contain the ‘src’ attribute.

For example:

embedded javascript

The bold text is the embedded JavaScript code.

As you can see the Google Analytics tracking code that you copy-paste on each web page contains embedded JavaScript.

You need to use script tags in order to use embedded JavaScript. JavaScript code placed outside the script tag will not execute.

Note: Every <script> tag must have the closing </script> tag and you can place script tags anywhere in the head or body section of an HTML document.

External JavaScript

External JavaScript is JavaScript added to an HTML document using the <script> tag which contains the ‘src’ attribute. For example:

External Javascript

Here all the JavaScript code is stored in an external JavaScript file and this file is called via the <script> tag.

External JavaScript is the recommended method to add JavaScript to an HTML document. You should avoid using inline and embedded JavaScript wherever possible.

There are three big advantages of using external JavaScript:

  1. Your JavaScript code does not interfere with other JavaScript code added to the same page and thus enable unobtrusive scripting.
  2. It becomes easier to maintain, debug, understand and reuse JavaScript code
  3. Cached JavaScript files can speed up page loads.

JavaScript statements

A JavaScript statement is an instruction which is executed by a web browser. Following is an example of a JavaScript statement for analytics.js.

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’);

Another example of a JavaScript statement:

ga(‘send’, ‘pageview’);

The same code for gtag.js will look like below

gtag(‘config’, ‘UA-XXXX-Y’);

Another example of a javascript statement for gtag.js:

gtag(‘event’, <action>, {

  ‘event_category’: <category>,

  ‘event_label’: <label>,

  ‘value’: <value>

});

The Google Analytics tracking code that you use so often is made up of a bunch of JavaScript statements:

javascript statements analytics js

Each JavaScript statement must end with a semicolon ;

So the following code is not valid:

missing semicolon analytics js

Now let’s understand this for gtag.js

In the following images, all underline statements are JavaScript statements in the global site tag (gtag.js).

javascript statements

Even if gtag.js is the new version of analytics implementation, the JavaScript rules are the same i.e. each JavaScript statement must end with a semicolon. The following code will not be valid.

missing semicolon

And the correct code will be

gtag(‘js’, new Date());

gtag(‘config’, ‘UA-119902729-1’);

This missing semicolon error may look trivial but it can easily create a hard to diagnose tracking issue. This is because it is not very easy to spot a tiny missing semicolon in a big piece of code.

Order of execution of JavaScript statements

JavaScript statements are executed in the order in which they are written. By default they are executed from top to bottom and from left to right.

Let’s understand how it applies to Analytics.js

execution order

Since JavaScript statements are executed from top to bottom, the following JavaScript statement in Google Analytics: ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); will execute before the statement ga(‘send’, ‘pageview’);

The order of execution is as important as the code itself. If you change the order of JavaScript statements, your code will start behaving differently or may stop working. For example, the following analytics.js code will not work

change in order

Here I have changed the order of the last two JavaScript statements in the Google Analytics tracking code.

The second last statement ga(‘send’, ‘pageview’); is the instruction to send pageview data to Google Analytics server. The last statement ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); is the instruction to create a tracking object and associate it with my web property.

Since I am trying to send pageview data to Google Analytics server before a tracking object is created, my Google Analytics tracking code will not work. So just by changing the order of JavaScript statements, you can stop code from working correctly.

The same principle applies to gtag.js as well. Each statement will execute according to its order placed.

execution order gtag

In the below image for gtag.js, I have interchanged the order of execution for two statements.

The first statement is window.dataLayer = window.dataLayer || []; which I have moved to last statement. And the second statement is gtag(‘config’, ‘GA_MEASUREMENT_ID’); 

In this case, my Pageview tag will fire but it won’t be able to capture the dataLayer values. This is because I have defined the dataLayer after the “config” command. Hence it will be an incomplete and incorrect implementation.

change in order gtag

JavaScript and white spaces

JavaScript ignores multiple white spaces.

So the statement for analytics.js, ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); can be written as:

ga          (‘create’,              ‘UA-XXXX-Y’,        ‘auto’)       ;

or like this

ga(

‘create’,

‘UA-XXXX-Y’,

‘auto’

);

Similarly the statement x=y+z; can be written as x = y + z ;

It is a good practice to put spaces around operators ( = + – * / ).

Use extra white spaces to increase the readability of your JavaScript code.

In general, the use of extra white spaces does not create any issue in your code. But there are some exceptions. For example, extra white space used inside a string can cause problems:

white space analytics

The web property ID used in your Google Analytics Tracking code is a string value (‘UA -XXXX-Y’).

When the web property ID contains extra spaces either before or after the ID then Google Analytics will not be able to recognize your web property ID and hence not be able to associate the tracking object with your web property.

As a result, your Google Analytics tracking code will not be able to send any pageview and user data to GA server. This is another error which may look trivial but can easily create a hard to diagnose tracking issue.

Similarly, in the case of gtag.js, the statement for Analytics.js gtag(‘config’, ‘GA_MEASUREMENT_ID’); can be written as:

gtag   (‘config’,      ‘GA_MEASUREMENT_ID’     );

or like this

gtag(

‘config’,

‘GA_MEASUREMENT_ID’,

);

Comments in JavaScript

Comments are used to add a note to a JavaScript code and to stop a JavaScript statement from being executed.

There are two types of comments in JavaScript:

  1. single-line comment
  2. multi-line comment

Single-line comments begin with two forward slashes ( // ) and run to the end of the line. For example:

single line comments

In the above image, ‘creates a tracker’ and ‘sends a pageview’ are the single-line comments added to the Google Analytics tracking code for analytics.js.

single line comments gtag

In the above image, ‘Configures GA property and sends pageview’ and ‘// Sends Sign in event’ are the single-line comments added to the Google Analytics tracking code for gtag.js

Note: Any text between // and the end of the line is ignored by JavaScript i.e. it is not executed.

A multi-line comment starts with /* and ends with */ .

For example:

multi line comment

Note: Any statements between /* and */ will not be executed by JavaScript. A forward slash is used whether a comment is a single-line or multi-line comment.

Comments are commonly used to stop a statement from being executed during testing.

For example following JavaScript statement for analytics.js won’t execute as it has been turned into a comment:

// setTimeout(“ga(‘send’,’event’,’Profitable Engagement’,’time on page more than 3 minutes’)”,180000);

Also, gtag.js statements won’t execute if they are turned into comments.

//gtag(‘event’, ‘sign in’, {‘method’: ‘Google’});

JavaScript Variables in analytics.js

Variables are used to store values. Creating a variable in JavaScript is called ‘declaring a variable’.

You can declare a variable in JavaScript by using the keyword ‘var’.

For example:

var _gaq; // create a variable and name it _gaq

Another example:

var pageTracker; // create a variable and name it pageTracker

Note: It’s a good programming practice to declare all variables at the beginning of a script/code.

Use the assignment operator ‘=’ to assign a value to a variable.

For example:

var _gaq;
_gaq = _gaq || []; // assign the value ‘_gaq || [];’ to the variable _gaq

Another example:

var pageTracker;
pageTracker = _gat._getTracker(“UA-12345-1”); /* assign the value _gat._getTracker(“UA-12345-1”) to the variable pageTracker */

You can also declare a variable and assign it a value at the same time. For example:

var _gaq = _gaq || [];

Another example:

var pageTracker = _gat._getTracker(“UA-12345-1”);

To use the value of a variable, just use the variable name without surrounding it with quotes (single or double quotes).

For example:

var videoName= ‘superman vs Batman’;
ga(‘send’, ‘event’, ‘videos’, ‘play’,videoName);

If you enclose a variable name in quotes (single or double quotes) then it will become a string value. For example:

var videoName= ‘superman vs Batman’;
ga(‘send’, ‘event’, ‘videos’, ‘play’,’videoName’);

Here ‘videoName’ is a string value and not the variable we declared earlier. So this event tracking code will pass ‘videoName’ as event label instead of passing ‘superman vs Batman’ as event label.

JavaScript Variables in gtag.js

Similar to the practice you can also declare variable in gtag.js

For example:

var pagepath; // create a variable and name it pagepath

Another example:

var scrollMilestone; // create a variable and name it scrollMilestone

You can assign it a value using the ‘=’ operator

For example, lets suppose you want to capture a page path (Complete URL) and send it in the event you can use a variable, as below.

var pagepath= window.location.href // define variable and assign the value of window.location.href

And when you send any event tag, you can just call the variable like below

gtag(‘event’, ‘scroll100’, {

  ‘event_category’: ‘engagement’,

  ‘event_label’: pagePath,

});

Naming JavaScript Variables

There are six characteristics of variable names in JavaScript:

  1. Variable names are case sensitive.
  2. Variable names can be alphanumeric.
  3. No spaces are allowed in a variable name.
  4. No special characters (other than $ and underscore) are allowed in a variable name.
  5. A variable name cannot begin with a number.
  6. A keyword cannot be used as a variable name.

#1 Variable names are case sensitive.
For example, the following are all different variables:

var pageTracker;
var pagetracker;
var PageTracker;
var PAGETRACKER;

#2 Variable names can be alphanumeric.
Example:

var alpha23;

#3 No spaces are allowed in a variable name.

Example:

var first name = ‘Himanshu’; // not valid

#4 No special characters (other than $ and underscore) are allowed in a variable name.
For example:

var _gaq = “Peter”; // underscore is allowed in a variable name
var US$ = 1500; // dollar sign is allowed in variable name
var First-name= “anna”; // hyphen is not allowed in a variable name

#5 A variable name can not begin with a number.
For example:

var 23alpha; // not valid

#6 A keyword can not be used as a variable name (more about keywords later).

Best practices for creating variable names in JavaScript

  • Use lower-case for variable names wherever possible.
  • Use either underscore to separate each word in variable name or use camel casing.

For example:

var first_name = ‘Himanshu’;
var firstName= ‘Himanshu’;

Note: In a camel case we capitalize the first letter of each word except the first word.

Attribution Modelling in Google Analytics and Beyond
Attribution Modelling in Google Ads and Facebook

Get my best selling books on Attribution Modelling

  • Learn to implement attribution modelling in your organisation
  • Understand the customer purchase journey across devices
  • Determine the most effective marketing channels for investment

 Click book covers to find out more

JavaScript Keywords

A keyword (or identifier) is a reserved word which carry special meaning.

Following are some examples of keywords in JavaScript:

  1. var
  2. function
  3. return
  4. for
  5. true
  6. false
  7. null
  8. undefined
  9. if

So,

var function; // not valid as ‘function’ is a keyword.
var positiveResult = true; // valid
var negativeResult = false; // valid

true and false are keywords in JavaScript. They are also boolean values. So you don’t need to put any quote marks around them.

If you put quote marks around them then they will become string values. For example:

ga(‘create’, ‘UA-XXXX-Y’, {‘allowLinker’: true}); // valid
ga(‘create’, ‘UA-XXXX-Y’, {‘allowLinker’: ‘true’}); /* not valid because ‘true’ is a string value and allowLinker doesn’t accept string */

For gtag.js same code will look like below

gtag(‘config’, ‘UA-XXXX-Y’, {

          ‘linker’: {

           ‘domains’: [‘example.com’]

  }

}); // Valid

Note: All JavaScript identifiers are case sensitive. So JavaScript does not interpret VAR or Var as the keyword var:

Var _gaq; // not valid
VAr _gaq; // not valid
VAR _gaq; // not valid
var _gaq; // valid

JavaScript Values

A JavaScript variable can store value of any data type. It can store:

  1. Numeric value (whole number, decimal number)
  2. String value
  3. Boolean value
  4. Undefined value
  5. null value
  6. Array
  7. Multidimensional array
  8. Object
  9. Array of Objects
  10. Other variables

For example:

Numeric Values

var a = 3;
a = 3.14159265;
a = -3;
a = -3.14159265;

Strings

a =’himanshu’;
a = “sharma”;

Boolean Values

a = true;
a = false;

Undefined value

a= undefined;

Null value

a = null;

Arrays

a = [1,2,3];
a= [[‘name’,’john’],[‘age’,20]];

Objects

a = {‘age’:24};
var dataLayer = [{‘name’:’john’,’age’:23}, {‘name’:’ash’,’age’:42}];

Other Variable

var half = 12;
var full = half * 2;

In JavaScript the datatype of a variable depends upon the value it has currently stored.

For example:

var _gaq; // _gaq is undefined
_gaq = 5; // Now _gaq has become a Number
_gaq= “John”; // Now _gaq has become a String
_gaq =true; // Now _gaq has become a boolean
_gaq=[]; // Now _gaq has become an array
_gaq ={}; // Now _gaq has become an object

Because of this flexibility in data types, JavaScript programs are highly prone to errors.

Strings in JavaScript

A string is a series of characters of any length.

Strings must be enclosed by single or double quote marks. For example:

var name = ‘Himanshu sharma’;
var name2 = “John lewis”;
var address = “28 station road”;
var emailAddress= ‘crazynitch[@]gmail[.]com’;

Note: Any character available on a keyboard can be used in a string including white spaces.

You can use quotes inside a string, as long as they don’t match the quotes surrounding the string.

Example-1:

Example-2:

example 2

Example-3:

example 3

Example-4:

var hhh = “Hunter “Hearst” Helmsley”; /* not valid because inner quotes match with surrounding quotes */

If you want to use quotes inside a string that match the quotes surrounding the string then you need to use backslash \ (also known as escaping character).

For example:

var hhh = “Hunter \”Hearst\” Helmsley”; // valid
hhh = ‘Hunter \’Hearst \’ Helmsley’; // valid

If you enclose a number in quotes (either single or double quotes), it will be treated as a string by JavaScript.

For example:

example 4

Needless to say, you need to be careful with how you use the quotes in your JavaScript code. You can make a perfectly valid number a string just by surrounding it with quotes.

JavaScript Arrays and Objects

An array is a special variable which can store multiple elements of same or different data types at a time.

These elements can be strings, numeric values, undefined values, boolean value, other arrays or objects.

javascript array

You can create an array in JavaScript by using the ‘new Array()’ function or via array literal notation [].

For example:

var cars = new Array();

or

var cars = [];

The datalayer that you use in Google Tag Manager is also a JavaScript array:

dataLayer = []; // empty data layer

Object is also a special variable which has got properties and methods.

object
exmple 5

Syntax for creating objects in JavaScript:

ObjectName={‘property1’:value1, ‘property2′:value2, …..’propertyN’:valueN};

Here property can be any string or identifier.

The datalayer that you use in Google Tag Manager is a JavaScript array of one or more objects. For example:

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’

}];

I have explained both Arrays and Objects in great detail in this article: Google Tag Manager Data Layer explained like never before. So check it out.

Functions in JavaScript

JavaScript function is a block of code which performs a particular task when it is executed.

A JavaScript function can not execute on its own. It needs to be called in order to be executed.  We use the keyword ‘function‘ to create a JavaScript function.

Following is the syntax for creating a function in JavaScript:

function <functionName>(parameter1, parameter2,….) {
Java Script Statement1
Java Script Statement2
.
.
Java Script StatementN

}

Here, Parameters are the names we list when defining a function.

Arguments are the values we pass when calling a function.

For example in the Google Analytics tracking code the names i,s,o,g,r,a,m are parameters and the values ‘window’, ‘document’, ‘script’, ‘//www.google-analytics.com/analytics.js’ and ‘ga’ are arguments:

parameters and arguments

Note: Using parameters and arguments is optional.

Following are the examples of functions used in tracking Twitter Social Interactions (clicks, tweets, follows) in Google Analytics:

// Define Call Back Functions
function clickEventToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Click’, window.location.href);
}

function tweetIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Tweet’, window.location.href);
}

function retweetIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Retweet’, window.location.href);
}

function followIntentToAnalytics() {
ga(‘send’, ‘social’, ‘Twitter’, ‘Follow’, window.location.href);
}

Note: Rules for creating function names is the same as the rules for creating variable names.

Google Analytics ‘ga’ function

Google Analytics uses it own in-built function known as the ‘ga’.

This function does almost every task in Google Analytics, whether it is creating a tracking object, sending pageview data, sending event data, ecommerce data etc.

ga command

The first argument of ‘ga’ function is a Google Analytics command (like ‘create’, ‘require’, ‘send’ etc)

The second and subsequent arguments depend upon the Google Analytics command being used:

ga command1

By passing different arguments to the ‘ga’ function, you can carry out different tasks in Google Analytics. For example:

ga(‘create’, ‘UA-XXXX-Y’, ‘auto’); // create a tracking object

ga(‘send’, ‘pageview’); // send pageview data to GA server

ga(‘send’, ‘event’, ‘videos’, ‘play’,’videoName’); // send event tracking data

ga(‘require’, ‘ecommerce’); // load ecommerce plugin

ga(‘require’, ‘ec’); // load the enhanced ecommerce plugin

ga(‘linker:autoLink’, [‘abc.com’, ‘xyz.com’]); // define which domains to auto link

ga(‘ec:addImpression’, // send product impression data
{
‘id’: ‘P12345’,
‘name’: ‘Android Warhol T-Shirt’,
‘category’: ‘Apparel/T-Shirts’,
‘brand’: ‘Google’,
‘variant’: ‘Black’,
‘list’: ‘Search Results’,
‘position’: 1,
‘dimension1’: ‘Member’
}
);

Since function names follow the same rules for naming variables, they are also case sensitive.

So if you use GA as in:

GA (‘create’, ‘UA-XXXX-Y’, ‘auto’); // not valid statement

Ga (‘create’, ‘UA-XXXX-Y’, ‘auto’); // not valid statement

ga (‘create’, ‘UA-XXXX-Y’, ‘auto’); // valid statement

Each function in Google Analytics has a fixed number of parameters which are allowed. If you try to add more parameters than allowed then this will cause tracking issues. For example:

When the ‘ga’ function is used to send ‘event’ data, then only four values are allowed: ‘event category’, ‘event action’, ‘event label’ and ‘event value’. Consequently, the following statement is not valid as it contains more parameters than allowed:

ga(‘send’, ‘event’’, ‘videos’, ‘play’,40, ‘full speed’); // not valid statement

Each function in Google Analytics accept arguments of a certain data type. So if you add an argument that is of a different data type, then this will cause tracking issues. For example:

analytics function

Similarly, each function in Google Analytics has a fixed number of required parameters, the parameters which you have to enter for a given method.

If you skip one of the required parameters then this can make the tracked data unreliable or your tracking may stop working. For example ‘Transaction ID’ is a required parameter when measuring product impressions in enhanced ecommerce tracking.

So if this parameter is not passed then the tracking code won’t work:

missing product id

Other important points to keep in mind regarding Google Analytics Functions in analytics.js:

#1 Use correct syntax for all the functions in Google Analytics.

For example, the names of all the functions (methods) in classic Google Analytics (ga.js) should begin with underscore _ . Otherwise, the functions will not execute and tracking will not work as intended. For example, use _trackPageView instead of trackPageView. In the case of universal analyticsuse ga instead of GA.

#2 Use only the active methods/functions found in the Google Analytics Library

Google Analytics depreciate certain methods from time to time. Methods once depreciated should no longer be used as they can negatively affect data quality. Review your Google Analytics Tracking codes periodically and make sure that you use only active methods.

You can find the list of all active methods for Universal Analytics from here: https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference 

You can find the list of all active methods for Classic Google Analytics from here: https://developers.google.com/analytics/devguides/collection/gajs/methods/

#3 Never add quotes (either single or double quotes) to a function argument that should not be quoted like numbers, boolean values, functions, arrays, objects, variable names etc.

Use quotes only when you want a value to be interpreted as a string. Otherwise, Google Analytics may incorrectly record data or fail to record data.

#4 Always refer to the Official Google Analytics Developers documentation

Whenever you are customizing your Google Analytics tracking code or implementing a certain type of GA tracking, always refer to the official GA developer’s documentation to make sure that you are using the correct syntax for your code.

GA developers documentation for Universal Analytics: https://developers.google.com/analytics/devguides/collection/analyticsjs/

GA developers documentation for Classic Google Analytics: https://developers.google.com/analytics/devguides/collection/gajs/

Google Analytics function used in gtag.js

The new version uses ‘gtag’ as a function. This is a built-in function for a new Google Analytics account. This also works while sending data to other products like Google Ads, Search 360, Campaign manager, etc.

As a first step, you need to add a global snippet to every page of your website and then use the gtag() function to capture events and send data.

gtag command

There are three types of command supported by gtag which are:

1) ‘config’ : used to establish general properties configuration settings for a particular product account (Google Analytics, Google Ads)

gtag (‘ config ‘, ‘UA-XXXXX-Y’); Sets the property and sends pageview.

2) ‘set’ : used to establish general parameters that will be associated with every subsequent event on the page

set gtag(‘set’, {‘currency’: ‘USD’});

3) ‘event’ : used to send event data to the analytics or ads properties

gtag(‘event’, ‘login’, { ‘method’: ‘Google’});

If you are using gtag.js as an implementation method, you need to follow the same rules which we have seen earlies for analytics.js. Since the JavaScript syntax are similar to both method.

Google Analytics Tracking Code

There are few things about Google Analytics tracking code which you need to remember in order to prevent tracking issues:

  • Make sure every web page on your website contains Google Analytics tracking code (GATC). Otherwise, you will get self-referral issues.
  • Avoid customizing the GATC if you don’t know what you are doing. You are most likely to break the code and the code once broken will stop working. Even a missing semicolon can break the code.
  • Never copy-paste the GATC from a word document as it can change the quotation marks in your tracking code which may stop the code from working.
  • If the GATC on a page is not the asynchronous version of the tracking code snippet then the reported data could be unreliable. So you need to upgrade to the asynchronous version of the tracking code.
  • There are many versions of GATC: urchin.js (oldest version), ga.js, dc.js and analytics.js (latest version). Installing multiple versions of the google analytics tracking code on a page can inflate pageview and users data and make them unreliable. So always use only one version of google analytics tracking code on a page at a time.
  • Keep the GATC inside the head section of a web page. This increases the likelihood that a tracking beacon is sent before a user leaves the page.
  • Make sure that you are using the correct GATC. Webmasters who manage multiple websites, sometimes add the GATC of another website.
  • Even if you place Google Analytics tracking code in an external script file, Google Analytics will continue to collect analytics data.
  • Each time GATC is executed, it sends an HTTP response to the GA server. But when GATC is not executed, no HTTP response is sent.

So if you see an error message ‘No HTTP response detected’ then it means either your browser is using some extension that doesn’t let the GATC from being executed or there is some syntax error in GATC.

My best selling books on Digital Analytics and Conversion Optimization

Maths and Stats for Web Analytics and Conversion Optimization
This expert guide will teach you how to leverage the knowledge of maths and statistics in order to accurately interpret data and take actions, which can quickly improve the bottom-line of your online business.

Master the Essentials of Email Marketing Analytics
This book focuses solely on the ‘analytics’ that power your email marketing optimization program and will help you dramatically reduce your cost per acquisition and increase marketing ROI by tracking the performance of the various KPIs and metrics used for email marketing.

Attribution Modelling in Google Analytics and BeyondSECOND EDITION OUT NOW!
Attribution modelling is the process of determining the most effective marketing channels for investment. This book has been written to help you implement attribution modelling. It will teach you how to leverage the knowledge of attribution modelling in order to allocate marketing budget and understand buying behaviour.

Attribution Modelling in Google Ads and Facebook
This book has been written to help you implement attribution modelling in Google Ads (Google AdWords) and Facebook. It will teach you, how to leverage the knowledge of attribution modelling in order to understand the customer purchasing journey and determine the most effective marketing channels for investment.

About the Author

Himanshu Sharma

  • Founder, OptimizeSmart.com
  • Over 15 years of experience in digital analytics and marketing
  • Author of four best-selling books on digital analytics and conversion optimization
  • Nominated for Digital Analytics Association Awards for Excellence
  • Runs one of the most popular blogs in the world on digital analytics
  • Consultant to countless small and big businesses over the decade