In the context of programming, there are three different types of layers (also called ‘logic’):
Presentation layer
Business layer
Data layer
#1 Presentation layer (or presentation logic)
The presentation layer corresponds to the user interface. It is used to manage interaction with the users.
The presentation layer is made up of one or more scripting languages.
The three scripting languages which are most commonly used for creating a presentation layer are HTML, CSS, and JavaScript.
HTML (or HyperText Markup Language) is used to develop text content of a presentation layer.
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.
When you interact with a web page, you are interacting with the presentation layer.
#2 Business layer (or business logic)
The business layer corresponds to business rules and workflows that determine how data can be created, stored and changed. The business layer sits between the presentation layer and the data layer.
#3 Data layer (or data logic)
The data layer corresponds to the data structure and database. The data layer should contain all the data you want to send to various analytics and/or marketing tags.
The data layer is used as the source of a vast amount of customer interaction data, website-related data and campaign data.
What is a data layer in the context of Google Tag Manager?
In the context of GTM, a data layer is a JavaScript array of a single object which is used:
To store all the key attributes of a web page like page title, page URL, page category, etc.
To store all the key information your marketing and analytics tags currently need, like user ID, client ID, user’s preferences, users’ purchase history, product ID, product price, etc.
To store all the key information you may need in the near future for additional tracking.
To send information from a website to the GTM container tag.
Why do you need a data layer?
A data layer provides a safer and reliable way to pull data from the presentation layer and send it to the container tag (aka GTM).
You can directly pull data from the presentation layer by traversing the HTML DOM (structure of HTML) using JavaScript and then sending the data to the container tag.
When you pull data directly from the presentation layer and push it into your analytics and marketing tags (via GTM), you create an unreliable tracking setup.
The problem with this approach is that the presentation layer can change any day, any time, without your knowledge, as commercial websites update all the time. As a result, any tag can stop working any day, any time, without any prior notice.
To fix the problem, we create and use data layers, which store all the information we want to collect about a web page:
Once you have set up a data layer, the container tag should be used to pull data from the data layer of a page instead of its HTML DOM (the presentation layer).
So no matter what happens to HTML DOM, the data layer will remain the same, and your tags will continue to work (unless, of course, someone/something breaks the data layer itself).
GTM is a really powerful tool and understanding the data layer is the key to getting the most out of Google Tag Manager.
What do you need to know in advance to use GTM Data Layers?
When you have used GTM for long enough, you know that the real power of GTM lies in the usage of variables, especially custom variables that require coding knowledge.
In order to understand the concept of a data layer, you would need to understand JavaScript arrays and objects.
When can you use DOM scraping instead of data layers?
Each tag management solution (TMS) provider implements the data layer slightly differently. So most likely, you won’t be able to use the same data layer with every TMS (if you use more than one TMS).
Data layers should be hard-coded on a website by your developer or IT team. So as long as you are using data layers, you may need to depend upon IT for its updates and maintenance.
DOM scraping is a technique used to pull data directly from the HTML elements (buttons, links, forms, etc) of a web page by using JavaScript and the knowledge of HTML DOM.
Almost all TMS vendors provide the functionality of scraping the HTML DOM. DOM scraping comes in handy when it is impossible to implement the required data layers in a reasonable amount of time to set up certain tracking.
You can implement TMS solutions faster through DOM scraping, as there is little to no dependence on IT, and you have more control over the implementation.
However, the TMS solution implemented through DOM scraping is not a stable solution, as changes in the HTML DOM (like a change in the ID of an HTML element) can quickly break the TMS solution.
So TMS solution deployment through DOM scraping is more of a quick fix when you lack development resources or time. It is not something you can/should rely upon for a long period of time or where a lot of money is at stake (like setting up tracking for an airline website).
What information should you store in a data layer?
If you want to avoid the hassle of modifying data layers every time you deploy a new GTM solution, you should aim to hard-code one universal data layer on each web page of your website. Each universal data layer should include all the key attributes of the web page on which it is embedded.
Your data layer should include all the key information your marketing and analytics tags currently need. It should also include all the key information you may need in the near future for additional tracking.
This information could be: #1 Page attributes
page title
page URL
page category, etc.
#2Product(s)’ attributes – attributes of a product(s) listed on a web page like:
product name
product id
product price
product category
product image URL
product variant (color, size, dimension) selected
product quantity selected
product views
product clicks (clicks on a product listing on a category page)
An array is a special variable that can store multiple elements, of the same or different data types, at a time.
A variable is a location in the computer memory which is used for storing data. A variable can store different data at different times.
For example, if ‘a’ is the name of a variable, then ‘a’ can be used to store a value like ’10’ and then, at a different point in time, can be used to store another value like ’20’.
a = 10;
a = 20;
However, a variable can store only one value at a time. If you want a variable to store more than one value at a time, then you need to use a special variable called an array.
An array is made up of one or more elements. These elements can be strings (like ‘hello’), numeric values (like 10), undefined values, Boolean values (like true, false), and other arrays or objects.
Creating an array variable via the array function
An array can be created using the array function or array literal notation [].
For example, here is how the empty array created through the array function will look like in JavaScript:
var a=new Array();
Here ‘a’ is the name of the array, and ‘var’ is a command used to create a variable in JavaScript. You can give any name to your array. For example:
var myArray = new Array();
Creating an array variable via array literal notation
The array literal notation method is preferred for creating an array.
For example:
var a= [];
//Or
a= [];
Here a =[] is an empty array.
Following is an example of an array variable that contains one element of type number:
a = [10];
Following is an example of an array variable that contains two elements of type number:
a = [10, 20];
Following is an example of an array variable that contains one element of type string:
a = [“Hello”];
Following is an example of an array variable that contains three elements of type String:
a=[“hi”,”bye”,”goodbye”];
Following is an example of an array variable that contains one element of type number and one element of type string:
a = [100, “Hello”];
Arrays that contain elements of different data types
An array variable can be used to store elements of different data types.
For example, you can create an array that contains both string and number values:
a1=["hi","bye","goodbye", 10, 20, 56];
Here, the array variable named ‘a1’ comprises six elements. Out of these six elements, the first three elements are of type string, and the last three elements are of type ‘number’.
You can also create an array like the one below:
a2=["hi",10,"bye",20, 56,"good bye"];
Here, the array variable named ‘a2’ comprises six elements. Out of these six elements, three elements are of type string, and the remaining three elements are of type ‘number’.
Note: Even when both a1 and a2 contain the same elements, they are still different array variables because the order of the elements is different.
Different types of array variables
Following are the different types of array variables:
Array of Strings
Array of numbers
Array of undefined values
Array of Boolean values
Array of objects
Array of array
Introduction to an array of Strings
Following is an example of an array of Strings:
a=["hi","bye","goodbye"];
The array variable ‘a’ has three elements named: ‘hi’, ‘bye’ and ‘goodbye’.
These three elements are of type String as they are String values. We call such arrays an array of Strings.
Introduction to an array of numbers
Following is an example of an array of numbers:
a=[10,24,56];
Here, all of these three elements have got numeric values. We call such arrays an array of numbers.
Array of undefined values
Following is an example of an array of undefined values:
a=[,,,]; // array of undefined values.
We use a comma in place of value to create an undefined value.
Array of Boolean values
Following is an example of an array of Boolean values:
a=[true,false]; // array of Boolean values
Array of array (or multi-dimensional array)
A multi-dimensional array is an array that contains one or more arrays.
For example:
a=[[“Clasicos”,57],[“Zapatos”,456]];
Here the array named ‘a’ contains the following two elements of type’ array’:
[“Clasicos”,57] [“Zapatos”,456]
Accessing the elements of an array
You can access an array element by referring to its index number. An Array index number starts with zero.
For example, consider the following array:
a=[10,24,56];
Here,
a[0] refers to the first element of the array, i.e. 10
a[1] refers to the second element of the array, i.e. 24
a[2] refers to the third element of the array, i.e. 56
Introduction to objects
Like an array, an object is also a special variable that can store multiple elements, of the same or different data types, at a time. However, unlike an array, an object’s element/property is in the format name:value.
Here, ‘name’ is the property name, and ‘value’ is the property value.
Creating an object variable via object literal notation
The object literal notation is the preferred method for creating an object.
For example:
var a= {};
//Or
a= {};
Here a ={} is an empty object.
Note: You can give any name to the JavaScript object.
Following is an example of an object variable that contains one element:
User = {“firstName”:”John”};
Following is an example of an object which contains two elements:
User = {“firstName”:”John”, “lastName”:”Marshall”};
Following is an example of an object which contains four elements:
User = {“firstName”:”John”, “lastName”:”Marshall”, “age”:85, “eyeColor”:”blue”};
Following is the syntax to create a JavaScript object:
Here ‘color‘ is the name of the property of the object ‘a’ and ‘Caf\u00e9‘ is the value of the ‘color’ property, which is a string.
a = {"price":164900.00};
Here ‘price‘ is the name of the property of the object ‘a’, and ‘164900.00’ is the value of the ‘price’ property, which is a numerical value.
a = {"color":"Caf\u00e9", "price":164900.00};
The object ‘a’ has two properties: ‘color’ and ‘price’.
Similarly, we can define an object with multiple properties:
a = {
"color":"Caf\u00e9", // the value is of type 'string'
"price":164900.00, // the value is of type 'numeric'
"sizeList":"", // the value is of type 'undefined'
"visitorsHasOrders":true, // the value is of type 'boolean'
"data":[45,67,89,20], // the value is of type 'array'
"shoppingCart":[["Clasicos",57],["Zapatos",456]], // the value is of type 'multi dimensional array'
"pageAttributes":{"page":"product"}, // the value is of type 'object'
"pageCategory":[ // the value is of type 'array of objects'
{"id":"20","name":"Zapatos"},
{"id":"53","name":"Masculino"},
{"id":"57","name":"Clasicos"},
{"id":"138","name":"Deportes"},
{"id":"139","name":"Masculino"}
{"id":"201","name":"Zapatos"},
{"id":"1244","name":"Mocasines"},
{"id":"1340","name":"Apaches"}
]
};
Accessing the elements of an object
You can access an object element/property by referring to its property name.
There are two methods to access object properties:
objectName.propertyName
or
objectName[“propertyName”]
For example, consider the following object:
User = {“firstName”:”John”, “lastName”:”Marshall”};
Here,
User.firstName refers to the first element of the object.
User.lastName refers to the second element of the object.
Similarly,
User[“firstName”] refers to the first element of the object.
User [“lastName”] refers to the second element of the object.
Difference between arrays and objects
Following is an example of an array that has the following three properties/elements: “Amit”, “Sinha”, and 35:
a = [“Amit”, “Sinha”, 35];
Since we use numbers to access array elements, we can access the first property of the array ‘a’ by the notation:
a[0];
We can re-write the array ‘a’ as the following object:
b = {“FirstName”: “Amit”, “LastName”:”Sinha”, “Age”: 35};
Here ‘b’ is an object that has the following three properties/elements:
“FirstName”: “Amit”
“LastName”:”Sinha”
“Age”: 35
Since we use property names to access object elements, we can access the first property of the object ‘b’ by the notation:
b.FirstName;
So while both arrays and objects are special variables that can store multiple elements (of the same or different data types), they store data in a different format and are accessed differently.
In JavaScript, arrays use numbered indexes whereas objects use named indexes.
Array of objects
An array variable can also be used to store one or more objects.
Following is an example of an array variable that contains only one object:
a=[{"id":"20","name":"Zapatos"}];
Here the object is: {“id”:”20″,”name”:”Zapatos”}
Following is an example of an array variable that contains two objects:
Types of variables that can be pushed into the data layer
Google Tag Manager supports different types of variables that can be pushed into a data layer.
These variables can be broadly classified into two categories: built-in variables and user-defined variables.
#1.Built-in variables
These are predefined and configured variables in GTM. They are ready to use variables.
A brand new GTM container is not enabled with built-in variables. To enable and use the various built-in variables, follow the steps below:
Step-1: Login to your GTM account.
Step-2: Click on the ‘Variables’ link in the left-hand side navigation menu.
Step-3: Click on the ‘Configure’ button:
Step-4: Click on the checkbox next to each variable name:
Once you enable the variables, they will automatically be available in the data layer.
Following are the various built-in variables available in GTM:
Pages
Page URL: Provides/returns the full URL of the current page. For e.g. “www.abc.com/products/newsunglasses”
Page Hostname: Provides the hostname portion of the current page. For e.g. if the current page is “www.abc.com/products/newsunglasses” then the ‘Page Hostname’ variable would return “www.abc.com”
Page Path: Provides the path portion of the current page. For e.g, if the current page is “www.abc.com/products/newsunglasses” then the ‘Page Path’ variable would return “/products/newsunglasses”
Referrer: Provides the full URL of the page which brought a user to the current page.
Utilities
Event: Gives details of current data layer events like DOM Ready, Page Load, Window Load, Click, etc
Environment Name: Returns the user-provided name of the environment currently being previewed.
Container ID: Provides the GTM container’s public ID. Example value: GTM-XXX12
Container Version: Provides the current version number of the container, as a String.
Random Number: Returns a random number value.
HTML ID: Returns the identifier of the custom HTML tag.
Errors
Error Message: This variable returns a string value that contains the error message displayed to a user.
Error URL: This variable returns a string value that contains the URL where the error occurred.
Error Line: This variable returns a numerical value or number of the line in the file where the error occurred.
Debug Mode: This variable returns true if the GTM container is currently in preview mode.
Clicks
Click Element: This variable returns the HTML element that was clicked.
Click Classes: This variable returns the value (of type String) of the ‘class’ attribute of the HTML element that was clicked.
Click ID: This variable returns the value (of type String) of the ‘ID’ attribute of the HTML element that was clicked.
Click Target: This variable returns the value (of type String) of the ‘target’ attribute of the HTML element that was clicked.
Click URL: This variable returns the string contained in the ‘href’ or ‘action’ attribute of the HTML element that was clicked.
Click Text: This variable returns the value of text clicked by a user.
Forms
Form Element: This variable returns the form element (like Dropdown, Radio Button, Text Box) that was clicked.
Form Classes: This variable returns the string contained in the ‘class’ attribute of the form element that was clicked.
Form ID: This variable returns the string contained in the ‘ID’ attribute of the form element that was clicked.
Form Target: This variable returns the string contained in the ‘target’ attribute of the form element that was clicked.
Form URL: This variable returns the string contained in the ‘href’ or ‘action’ attribute of the form element that was clicked.
Form Text: This variable returns the text provided by a user in a form field
History
These variables are used to track virtual page views when there is no change in URL.
New History Fragment: This variable returns the string value of the fragment (aka hash) portion of the page’s URL after the history event.
Old History Fragment: This variable returns the string value of the fragment (aka hash) portion of the page’s URL before the history event.
New History State: This variable returns the value of the state object that the page pushed onto the history to cause the history event.
Old History State: This variable returns the value of the state object that was active before the history event took place.
History Source: This variable returns a string that refers to the event that initiated the history change.
Videos
Video Provider: This variable returns the name of the video provider (i.e. YouTube).
Video Status: This variable returns the current state of video like play, pause, stop, buffering etc.
Video URL: This variable returns the URL of the embedded video, e.g. ‘https://www.youtube.com/watch?v=optimisesmart’.
Video Title: This variable returns the title of the embedded video.
Video Duration: This variable returns the total duration of a video in seconds.
Video Current Time: This variable returns an integer that represents the time in seconds where a user currently is.
Video Percent: This variable returns an integer that represents the percentage of the video watched by a user.
Video Visible: This variable returns true or false, depending upon if the video was visible in the browser viewport.
Scrolling
Scroll Depth Threshold: This variable returns a numeric value from 0 to 100 specified as the scrolling threshold.
Scroll Depth Units: This variable returns either ‘pixels’ or ‘percent’ depending upon which threshold type a trigger is tracking.
Scroll Direction: This variable returns the direction of the scroll with a string value like “Vertical” or “Horizontal”.
Visibility
Percent Visible: This variable returns a numeric value (0-100) that indicates how much of the tracked element has been in the browser viewport when the trigger fires.
On-Screen Duration: This variable returns a numeric value that indicates how many milliseconds the tracked element has been in the browser viewport when the trigger fires.
#2. User-defined variables
User-defined variables are custom created variables to suit specific requirements that are not covered by built-in variables. You can access the user-defined variables in the variables menu.
To create a new user-defined variable, follow the below steps
Step-1: click on the ‘Variables’ tab and click on ‘New’ under ‘User-Defined Variables’.
Step-2: A new window will pop up, like below. Give it a proper name and click on ‘Variable configuration’.
Step-3: In Variable Configuration, you will see several types of user-defined variables as below (Click on the type of variable you want to create).
The following list will give you an idea of supported user-defined variables
Navigation:
HTTP Referrer: This variable returns “Previous Page URL” or Referrer (Type of value: String)
URL: Current URL: This variable returns the current URL of a page loaded on the website (Type of Value: String)
Page variables:
1st party cookie: This variable returns the cookie value set in with a specific domain name (Type of value could be string or number, based on business requirement).
Custom JavaScript: This variable is a custom JavaScript function used to pass website parameters in a variable.
Data layer: The data layer variable corresponds to an array of values collected across your site and the visitor interactions and events that are tracked.
Page elements:
Auto-event variable: this variable identifies auto events like click, form submission, element visibility on the website and returns parameters associated with the event.
DOM element: This variable returns the value of the text of the DOM (Document Object Model) element or the value of the specified DOM element attribute on the page.
Element visibility: This variable returns the value to True for a specified object when it’s visible, like a pop-up. It also returns the percentage of the element’s visibility, like 50%.
Utilities:
Constant: This variable returns a constant number.
Custom event: This variable returns the custom event sent to dataLayer.
Environment name: Returns the user-provided name of the environment currently being previewed.
Google Analytics settings: This variable returns the Google Analytics Account ID.
Lookup table: This variable, based on certain conditions, evaluates the condition first and then accordingly sets a value of a specific variable.
Random number: This variable returns a random number between 0 and 2147483647.
RegEx table: this variable is an advanced version of the lookup table, which runs on regular expressions.
Google Tag Manager uses the array variable name called ‘dataLayer’
So if you want to create an empty data layer array, it would look like the one below:
dataLayer=[];
Since this line of code is a JavaScript statement, you need to enclose it within the <script> and </script> tags so that you can embed the code into your HTML document.
So the final setup will look like the one below:
<script>
dataLayer=[];
</script>
Congratulations, you just created your first data layer.
Note: A data layer is also known as dataLayer queue, dataLayer object, and data collection layer.
Data layer is an array of a single object
In the context of Google Tag Manager, a data layer is usually an array of a single object:
dataLayer=[{}];
Since this line of code is a JavaScript statement, you need to enclose it within the <script> and </script> tags so that you can embed the code into your HTML document.
So the final setup will look like the one below:
<script>
dataLayer=[{}];
</script>
Following is an example of a data layer which contains one element:
dataLayer = [{ ‘pageCategory’: ‘Statistics’ }];
Following is an example of a data layer that contains two elements:
Appending/passing messages onto the data layer queue => Adding data layer variables to the data layer.
Updating data layer => adding/updating/removing data layer variables.
Pushing information into the data layer => adding data layer variables to the data layer.
How is information pushed into a data layer?
Two methods can be used to push information into a data layer:
#1 By hard-coding the data layer variables in the data layer, preferably above the container tag.
#2 By dynamically adding objects to your data layer through the ‘push’ method of dataLayer object.
Use the first method to push information into a data layer on page load. For example, for ecommerce tracking or enhanced ecommerce tracking, we use the first method, as we want the ecommerce data to be available on page load.
Use the second method to push information into a data layer on any event other than the page load. For example, if you want to push information into the data layer on clicking the ‘Add to Cart’ button, use the second method.
The ‘push’ method of dataLayer object
Through the ‘push’ method of dataLayer object, you can dynamically add the object(s) to your data layer. The pushed object can contain one or more data layer variables.
This is the same as the dataLayer.push() method but with an added advantage.
‘dataLayer’ is a global JavaScript array variable and can thus be accessed by any function that can also access the window object. The advantage of using the ‘window’ prefix is that you can avoid conflict with any local JavaScript array variable that uses the ‘dataLayer’ name.
There are two types of scope in JavaScript: local scope and global scope. Scope determines the accessibility of JavaScript variables.
A variable declared within a JavaScript function is called a local variable. A local variable has local scope and can only be accessed within the function where it is declared.
A variable declared outside any function is called a global variable. A global variable has global scope and can be accessed by any function.
Note: In JavaScript, objects and functions are also called variables.
Multiple initializations of a data layer leads to overwriting of the data layer
Let us suppose the following data layer is hardcoded in the head section (<head>….</head> of a web page
<script>
dataLayer = [{‘pageCategory’: ‘Statistics’}];
</script>
Let us suppose, you later, hardcoded second data layer somewhere in the body section (<body>….</body>) of the web page:
<script>
dataLayer = [{‘visitorType’: ‘high-value’}];
</script>
Now what will happen on page load is that only the data from the second data layer will be available to the GTM container tag. The second initialization of the data layer will overwrite the first one. So if you want to access the ‘pageCategory’ data layer variable from within GTM, you won’t be able to. Because on page load, the data layer will look like this:
<script>
dataLayer = [{‘visitorType’: ‘high-value’}];
</script>
Instead of:
<script>
dataLayer = [{
‘pageCategory’: ‘Statistics’,
‘visitorType’: ‘high-value’
}];
</script>
In order to avoid this issue, do not initialize a data layer more than once on the same webpage. If you want to push new information to the existing data layer then use the ‘window.push()’ method. For example,
Now the final data layer after the push will look like the one below:
<script>
dataLayer = [{
‘pageCategory’: ‘Statistics’,
‘visitorType’: ‘high-value’
}];
</script>
Push information into a data layer only if the ‘dataLayer’ variable has already been declared
To avoid multiple initializations of a data layer and consequently overwriting the data layer with new information, always check whether the dataLayer variable has already been declared. If the dataLayer variable has already been declared, only then proceed to push new information. You can achieve this objective by using the following code:
If the dataLayer variable has not already been declared then assign a new empty array variable to it and only then proceed to push new information. You can achieve this objective by using the following code:
Now, the final data layer will look like the one below:
<script>
dataLayer = [{
‘pageCategory’: ‘Statistics’,
‘visitorType’: ‘high-value’
}];
</script>
Overwriting the value of an existing data layer variable
By pushing a variable of the same name as an existing variable but with a new value to the data layer. Let us suppose this is your existing data layer:
Data layer for ecommerce tracking (ecommerce data layer variables)
The data layer which contains ecommerce data layer variables is called the ecommerce data layer.
Following are the examples of ecommerce data layer variables that GTM recognizes:
currencyCode
impressions
ecommerce
click
actionField
products
detail
add
remove
promoView
promotions
promoClick
checkout
checkout_option
purchase
refund
id
affiliation
revenue, etc
Note: All the ecommerce data layer variables are reserved words (identifiers). They all carry a special meaning and therefore should not be used as a regular variable name in data layers while using GTM.
The ecommerce data layer pulls ecommerce data from your shopping cart (via a server-side script) and then sends the data to GTM.
Following is an example of an ecommerce data layer:
<script>// Send transaction data with a pageview if available// when the page loads. Otherwise, use an event when the transaction// data becomes available.
dataLayer.push({'ecommerce':{'purchase':{'actionField':{'id':'T800',// Transaction ID. Required for purchases and refunds.'affiliation':'OptimizeSmart','revenue':'998.00',// Total transaction value (incl. tax and shipping)'tax':'199.6','shipping':'1.9','coupon':'WINTER_SALE'},'products':[{// List of productFieldObjects.'name':'62 points GA Checklist',// Name or ID is required.'id':'62','price':'18.55','brand':'Optimize Smart','category':'eBook','variant':'Blue','quantity':1,'coupon':''// Optional fields may be omitted or set to empty string.},{'name':'9 points social media checklist','id':'9','price':'19.75','brand':'Optimize Smart','category':'eBook','variant':'Green','quantity':1}]}}});</script>
Note: All the ecommerce data layer variables are highlighted in the code in bold text.
Ecommerce data layers contain server-side code
The ecommerce data layer that you saw earlier and the ecommerce data layers that you see in the Google help documentation are all example codes. You can’t just copy-paste them on your website and then expect the ecommerce tracking to work.
To make your ecommerce data layers work and collect ecommerce data, you would need to add a server-side script (like PHP).
For example, here is what a data layer with a server-side script may look like:
This is what a hardcoded ecommerce data layer looks like. You would need the help of a web developer to create ecommerce data layers.
What format should the information you push into a data layer be in?
The information you push into a data layer, from either the front-end or back-end, must be in the format GTM can understand.
For example, if you try to push ecommerce data layer variables into a data layer that is not recognized/recommended by GTM, then your ecommerce tracking won’t work.
Note: ‘id’ is an example of an identifier (reserved word). So it carries a special meaning and should not be used as a regular data layer variable name while using GTM.
Naming conventions for data layer variables
You should use a consistent naming convention for data layer variables. If you use different variable names that refer to the same variable on different pages, GTM may not be able to fire tags in all the desired locations. For example,
If you set up the page category for the ‘signup’ page by using the ‘pageCategory‘ data layer variable, then the page category for the product purchase page should also be set up by using the ‘pageCategory‘ data layer variable and not by using data layer variables like ‘Pagecategory’ or ‘PageCategory’. That is because data layer variable names are case sensitive.
So the following set up won’t work the way, you think it should:
Data layer variable names should be enclosed in quotes
window.dataLayer.push({pageCategory: 'members-signup'}); // Won't work
window.dataLayer.push({'pageCategory': 'members-signup'}); // works
The name ‘Data Layer’ itself is case sensitive
So, ‘dataLayer‘ is different from ‘datalayer‘, and using the latter won’t work.
For example:
window.datalayer.push({'pagecategory': 'members-signup'}); // Won't work
window.dataLayer.push({'pageCategory': 'members-signup'}); // works
What is an ‘event’ data layer variable?
It is a special data layer variable used with JavaScript event listeners. It is used to fire a tag when a user interacts with webpage elements such as form, button, links, etc.
The syntax for setting up an event:
window.dataLayer.push({'event': 'event_name'});
Here’ event’ and ‘event name’ are strings.
For example, the following code update the data layer’s ‘event’ variable when a user clicks on a button:
Here ‘pageCategory’ is a data layer variable, whereas ‘visitorType’ is a dynamic data layer variable, as it has been pushed dynamically into the data layer during run time.
Note: Dynamic data layer variables are not hard-coded on a web page.
How can you rename a data layer (or data layer object)?
The default name of the data layer (or data layer object) is ‘dataLayer’.
By making a small change (highlighted below in bold text) in your GTM container code snippet you can rename your data layer:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','addYourNewDataLayerNameHere','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
For example:
<body>
<script>
SmartDataLayer = [{
'pageCategory': 'signup',
'visitorType': 'high-value'
}];
</script>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','SmartDataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
You should rename your data layer when you use multiple GTM container tags on the same web page, and you don’t want each GTM container tag to use the same data layer.
For example:
<body>
<script>
dataLayer1 = [{
'pageCategory1': 'signup',
'visitorType1': 'high-value'
}];
</script>
<!-- Google Tag Manager Container-1-->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer1','GTM-XXXX');</script>
<!-- End Google Tag Manager Container-2 -->
<!--===================================================================-->
<script>
dataLayer2 = [{
'pageCategory2': 'signup',
'visitorType2': 'high-value'
}];
</script>
<!-- Google Tag Manager Container -2 -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer2','GTM-XXXX');</script>
<!-- End Google Tag Manager Container-2 -->
<!--=====================================================================-->
<script>
dataLayer3 = [{
'pageCategory3': 'signup',
'visitorType3': 'high-value'
}];
</script>
<!-- Google Tag Manager Container-3 -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer3','GTM-XXXX');</script>
<!-- End Google Tag Manager Container-3 -->
<!--===================================================================-->
Note: By default, each GTM container tag uses a common data layer.
FAQ
Q. Do you need to be a web developer in order to use the data layer?
A. I am often asked this question. The answer is ‘no’, not for the very basic data layers. But you still need a basic knowledge of HTML, DOM, and JavaScript.
Q. When do you need a web developer to write data layers?
A. When you have to create complex data layers, like the one which pulls ecommerce data from the back-end (server-side) and converts that data into a format which GTM can understand.
What is a data layer snippet?
A data layer snippet is the data layer enclosed within <script> ….</script> tags.
It is the code used to create a new Google Tag Manager container tag. A container tag holds all the marketing/analytics tags, triggers, and variables for your website. When installing Google Tag Manager on your website, you are basically installing a container tag.
Following is an example of a container tag snippet:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
Note: The container tag snippet should be placed on every web page of your website.
Where should you place the data layer snippet?
The data layer snippet should be placed above your GTM container tag snippet in the head section (<head>….</head>) of a web page:
For example:
<head>
.
.
.
<script>
dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];
</script>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
</head>
<body>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager -->
Why should the data layer snippet be placed above the GTM container snippet?
If you place the data layer snippet below the container tag snippet, then the data layer variables may not be available to the container tag.
For example, the following set up may not work:
<!-- Google Tag Manager -->
...
<!-- End Google Tag Manager -->
<script>
dataLayer = [{'pageCategory': 'Statistics','visitorType': 'high-value'}];
</script>
Here the data layer variables’ pageCategory’ and ‘visitorType’ may not be available to the GTM container, as the data layer code has been placed after the container snippet.
FAQs
Q. When does Google Tag Manager function best?
A. When used alongside a data layer. You should know this by now!
Q. Is it mandatory to declare the data layer while using GTM?
A. No. Explicitly declaring a data layer is optional.
Q. Can you use GTM without explicitly implementing the data layer?
A. Yes. In that case, the GTM container code will automatically create its own empty data layer object for you.
Do you need a GTM container tag to implement a data layer?
No. You can create a JavaScript array that stores all the information you want to collect about a page and use it as a data layer. For example:
Q. How you can selectively fire tags on page load?
A. Through GTM triggers.
Q. What is the downside of not using the data layer?
A. You cannot use ‘events’ without a data layer, and above all, your GTM implementation could be pretty shaky.
Q. How you can access values from a page without implementing the data layer?
A. By using GTM custom JavaScript variables.
How can you implement a data layer on a web page?
By adding the following snippet of code above the container tag snippet in the head section <head>….</head> of your HTML document:
<script>
dataLayer = [];
</script>
For example, you might want to set data layer variables to indicate that the page is a ‘Maths’ page and that the visitor is a ‘high-value’ visitor. To do this, you initialize the data layer as follows:
A. Data layer variables are page specific. That means they exist as long as a user remains on the same page.
Q. How you can declare data layer variables that are relevant across pages?
A. By using the same data layer variable name on multiple pages of your website.
A real-life example of a data layer being used on a website
<script type="text/javascript">
var dataLayer = [{
"color":"Caf\u00e9",
"deviceAgent":"Mozilla\/5.0 (Windows NT 6.3; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/35.0.1916.153 Safari\/537.36"
"deviceOs":"non-mobile",
"deviceTheme":"desktop",
"deviceType":"desktop",
"gender":"Masculino",
"googleRemarketingLabel":"",
"image":"http:\/\/static.dafyty.com.co\/p\/brahma-6338-0822-1-product.jpg",
"pageAttributes":{"page":"product"},
"pageBrand":[{"id":"2","name":"Brahma"}],
"pageCategory":[
{"id":"20","name":"Zapatos"},
{"id":"53","name":"Masculino"},
{"id":"57","name":"Clasicos"},
{"id":"138","name":"Deportes"},
{"id":"139","name":"Masculino"},
{"id":"201","name":"Zapatos"},
{"id":"1244","name":"Mocasines"},
{"id":"1340","name":"Apaches"}
],
"pageMainCategory":"id":"1340","name":"Apaches"},
"pageName":"product",
"pageProductDescription":"<i>Zapatos<\/i> <b>Brahma<\/b> cafe, elaborados en cuero con costuras visibles en la zona delantera la cual es redonda. Forro en cuero y suela en goma. Un calzado muy comodo que puedes combinar tanto con tus atuendos formales como informales.",
"pageProductName":"Zapatos Brahma Cafe",
"pageTitle":null,
"price":"164900.00",
"priceDiscount":"12%",
"season":"Todas las temporadas",
"seasonYear":"2012",
"shopAnalyticsAccount":"",
"shopName":"default",
"sizeList":"",
"sku":"BR002SH19DJS",
"specialPrice":"144900.00",
"urlPageProduct":"http:\/\/www.dafiti.com.co\/Zapatos-Brahma-Cafe-280.html",
}];
dataLayer = CookieTracking.changeGtm(dataLayer);
</script>
And here is what this data layer looks like in the Google Developer’s Tools console tab:
Looking at this screenshot closely, you can see that all data layer variables are reported in alphabetical order in the developer’s tool console tab. That’s how you should write your data layer variables in alphabetical order. This way, the debugging of the data layer becomes easier.
Another thing worth noting is that the data layer above contains some dynamic data layer variables near the end like VisitorsAge, VisitorsEmail, VisitorsGender, etc. These data layer variables weren’t hard-coded on the web page but were dynamically pushed into the data layer via the push method.
How to check the data layer in Google Chrome Console
You can see the data layer on any web page via the console tab of the Google Developer’s Tool.
To do that, follow the steps below:
Step-1: In Google Chrome, right-click on a web page (the page must have Google Tag Manager installed) and then select ‘Inspect‘ from the drop-down menu:
This should open up the Google Developer’s Tool window at the bottom of your screen:
Step-2: Click on the ‘Console‘ tab at the top right of the tool window and then type ‘dataLayer’ at the command prompt:
You should now see a line of code just below the dataLayer:
Click on this line of code. You should now see all the data layer variables:
Click on a data layer variable to see more details about that variable:
gtm.js is a JavaScript library file used by the GTM container tag. If this library file doesn’t load, your GTM won’t work. Once the gtm.js library file is loaded, the container tag passes the event ‘gtm.js‘ to the data layer.
gtm.dom is a DOM file used by the container tag. If this file doesn’t load, it means DOM has not loaded. Once the DOM is loaded, the container tag passes the event ‘gtm.dom‘ to the data layer.
gtm.load is a load file used by the container tag. If this file doesn’t load, it means the window and all its contents are not loaded. Once the window and all its contents are fully loaded, the container tag passes the event ‘gtm.load‘ to the data layer.
These events are fired in the following sequence: gtm.js > gtm.dom > gtm.load
Every data layer gets these three events from the container tag. If your data layer doesn’t get any/all of these events, it means something has gone wrong with your tag manager implementation. It could either be a broken container tag, a broken data layer, or both.
If you have a hard-coded data layer on a page, the developers’ tool window will show you at least four JavaScript objects. One JavaScript object would be your data layer, and the other three will be the default JavaScript event objects:
How to implement data layer variables in Google Tag Manager
So, information sent in the data layer on the website can be used as custom triggers and also as user-defined variables in GTM. Follow the below steps to create a data layer variable.
Step-1: Log in to your Tag Manager Console.
Step-2: Click on the ‘Variables’ tab on the left side of the console:
Step-3: Scroll down to user-defined variables, click on ‘New’ as shown below:
Step-4: A screen like below will appear, where you can configure the variable type:
Step-5: On the left-hand side, you will see an overlay when you click on choose a variable type. Select the data layer variable from the options provided:
Step-6: Set pageCategory in the data layer variable name and click on ‘Save’:
Note that the ‘Data Layer Variable Name’ field is case sensitive.
How to check data layer in Google Tag Manager
To check or validate your data layer, you can use the Google Tag Manager preview tool.
Login to the Tag Manager console. Click on ‘Preview’:
You will now be automatically redirected to a new tab in your browser window. Enter the URL of your website and then click on the ‘Connect’ button:
You will now be automatically redirected to your website. Navigate back to the GTM preview window and then click on the ‘continue’ button:
You should now see a screen like the one below:
You will see the summary on the right-hand side, which gives the list of events happening on the page. As we have seen till now, we can update the data layer for any of the events dynamically by using dataLayer.push method.
Select an event for which you would like to see the data layer value and click on the ‘Data Layer’ Tab:
For the selected event, you can now see the dataLayer value after the Container loaded event fired:
You can see in the above image we can see two variables are initialised, which are
pageCategory: has value “Home”
visitorType: has value “high-value”
You can also verify the data layer variable in the Variables tab for the same events, which will give you the list of variables loaded when the events are fired and the value each variable is assigned. Just click on the variable for the corresponding event you want to check:
You can see in the below image that on Container Loaded we have a few of our variables assigned with a value. The event, Page Hostname, Page Path, Page URL and Referrer are the predefined variables from Google Tag Manager.
Page Category and Visitor Type are the data layer variables.
Note: Preview mode is not visible if you use extensions like Ghostery.
1) To store all the key attributes of a web page (like page title, page URL, page category, etc.) 2) To store all the key information your marketing and analytics tags need (like user ID, client ID, user’s preferences, purchase history, product ID, product price, etc.). 3) To store all the key information you may need in the near future for additional tracking. 4) To send information from a website to the GTM container tag.
Google Tag Manager uses the array variable name called ‘dataLayer’.
Why do you need a data layer?
A data layer provides a safer and more reliable way of pulling data from the presentation layer and sending it to the container tag (aka GTM). You can directly pull data from the presentation layer by traversing the HTML DOM (structure of HTML) using JavaScript and then sending the data to the container tag.
When you pull data directly from the presentation layer and push it into your analytics and marketing tags (via GTM), you create an unreliable tracking setup. The problem with this approach is that the presentation layer can change any day, any time, without your knowledge, as commercial websites update all the time. As a result, any tag can stop working any day, any time, without any prior notice.
To fix the problem, we create and use data layers, which store all the information we want to collect about a web page. Once you set up a data layer, the container tag should be used to pull data from the data layer of a page instead of its HTML DOM (the presentation layer). So no matter what happens to HTML DOM, the data layer will remain the same, and your tags will continue to work (unless, of course, someone/ something breaks the data layer itself).
How is information pushed into a data layer?
Two methods can be used to push information into a data layer:
#1 By hard coding the data layer variables in the data layer, preferably above the container tag.
#2 By dynamically adding objects to your data layer through the ‘push’ method of dataLayer object.
What is an array?
An array is a special variable that can store multiple elements of the same or different data types at a time. A variable is a location in the computer memory used for storing data. A variable can store different data at different times. However, a variable can store only one value at a time. If you want a variable to store more than one value at a time, you need to use a special variable called ‘array’.
An ‘array’ is made up of one or more elements. These elements can be strings (like ‘hello’), numeric values (like 10), undefined values, boolean values (like true, false), and other arrays or objects.
How do you create an array variable?
An array can be created using the array function or array literal notation. The array literal notation is preferred for creating arrays.
Register for the FREE TRAINING...
"How to use Digital Analytics to generate floods of new Sales and Customers without spending years figuring everything out on your own."
Here’s what we’re going to cover in this training…
#1 Why digital analytics is the key to online business success.
#2 The number 1 reason why most marketers are not able to scale their advertising and maximize sales.
#3 Why Google and Facebook ads don’t work for most businesses & how to make them work.
#4 Why you won’t get any competitive advantage in the marketplace just by knowing Google Analytics.
#5 The number 1 reason why conversion optimization is not working for your business.
#6 How to advertise on any marketing platform for FREE with an unlimited budget.
#7 How to learn and master digital analytics and conversion optimization in record time.
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
Get My Step-By-Step Blueprint For Finding The Best KPIs (32 pages ebook)
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.