Google Tag Manager Data Layer explained like never before

 

Index

#1 What is a dataLayer? #13 What are dynamic data layer variables?
#2 Understanding JavaScript Arrays to create data layers #14 How you can rename a data layer (or data layer object)?
#3 Understanding Javascript objects to create data layers #15 When you need to rename your data layer?
#4 Why do you need a data layer? #16 What is data layer snippet?
#5 Data Layer vs DOM Scraping #17 What is container tag snippet?
#6 What are data layer variables? #18 Where the data layer snippet should be placed?
#7 How you can initialize a data layer? #19 Why the data layer snippet must be placed above the container snippet?
#8 How information is pushed into a data layer? #20 Do you need a container tag to implement a data layer?
#9  What should be the format of the information you push into a data layer? #21 How you can implement data layer on a web page?
#10 How you can overwrite the value of existing data layer variable? #22  What information you should store in a data layer?
#11  Naming convention for data layer variables #23  How to see and interpret the data layer on a web page?
#12  What is ‘event’ data layer variable?   

 

If you have used Google Tag Manager (GTM) any longer than few days, you know that GTM does require good knowledge of HTML, DOM and JavaScript as prerequisite.

If you have implemented Ecommerce Tracking via GTM or enhanced ecommerce tracking via GTM, you know that you need the help of a web developer to create data layer for you.

If you have used GTM long enough, you know that the real power of GTM lies in the usage of variables esp. custom variables which require coding knowledge.

GTM is a really powerful tool and understanding the data layer is the key to getting the most out of Google Tag Manager.

 

What is a dataLayer?

Data layer is simply a JavaScript array which is used to store information and send information to Google Tag Manager container.

Example of empty dataLayer:

<script>

dataLayer = [];

</script>

Example of dataLayer which contain variables:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’

}];

</script>

In order to understand the concept of data layer, you first need to understand javascript arrays and objects.

Note: Data layer is also known as dataLayer queue, dataLayer object and data collection layer.

 

Understanding JavaScript Arrays to create data layers

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.

An array can be created by either using the array function or array literal notation []. The array literal notation is preffered for creating arrays.

For example, here is how the empty array created through array function will look like:

var a=new Array();

You can create the same array through array literal notation [] like this:

var a= [];

Or

a= [];

Google tag manager uses the array variable name called ‘dataLayer’. So if you want to create an empty data layer array, it would be like this:

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 in your HTML document.

So the final setup will look like this:

<script>

dataLayer=[];

</script>

Congratulations, you just created your first data layer.

Let us create a new array which has got three elements;

a=[“hi”,”bye”,”good bye”];

This array has got three elements named: ‘hi’,’bye’ and ‘good bye’. All of these elements are of type ‘string’ as they are string values. We call such array as array of strings.

Similarly, we can create a new array which has got three numeric values;

a=[10,24,56];

We call such array as array of numbers.

 

Other array examples:

a=[,,,] // array of undefined values. Use comma in place of value to create an undefined value.

a=[true,false]; // array of boolean values

a=[[“Clasicos”,57],[“Zapatos”,456]]; // array of arrays. Also known as multi dimensional arrays. It is an array which contains one or more arrays.

Following is an example of array of objects

a=[

{“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”}

];

You can also create array which contains elements of different data types:

a=[“size”, 10, true,[“Clasicos”,57],{“id”:”20″,”name”:”Zapatos”}];

White spaces and line breaks are not important. So to improve readability you can write the same ‘a’ array as:

a=[

“size”,

10,

true,

[“Clasicos”,57],

{“id”:”20″,”name”:”Zapatos”}

];

Since dataLayer is javascript array, you can create a data layer like the one below:

dataLayer=[“size”, 10, true,[“Clasicos”,57],{“id”:”20″,”name”:”Zapatos”}];

Congratulations, you just created your second data layer which is made up of 5 elements.

Note: The data layer used for GTM is usually an array of a single object: dataLayer = [{……}];

 

Understanding Javascript objects to create data layers

Javascript object is a variable which has got properties and methods.

Following is the syntax to create a javascript object:

 <object-name>={“property1”:value1, “property2″:value2, …..”propertyN”:valueN};

Here property can be any string or identifier.

An identifier is a reserved word which carry special meaning and can not be used as a variable name . For example ‘event’ is an identifier.

Property’s value can be a string, numeric value, undefined value, boolean value, array, multi dimensional array, object or array of objects.

The following example creates an empty object with no properties.

objA = {}; 

The following example creates an object called “user” and adds 4 properties to it:

user={“firstName”:”John”, “lastName”:”Marshall”, “age”:85, “eyeColor”:”blue”};

White spaces and line breaks are not important. So to improve readability you can write the same ‘user’ object as:

 user={

“firstName”:”John”,

“lastName”:”Marshall”,

“age”:45,

“eyeColor”:”blue”

};

 

Other examples of javascript objects:

objA = {“color”:”Caf\u00e9″};

Here ‘color’ is the property of the object ‘objA’ and ‘Caf\u00e9’ is the value of the ‘color’ property which is a string.

objA = {“price”:164900.00};

Here ‘price’ is the property of the object ‘objA’ and ‘164900.00’ is the value of the ‘price’ property which is a numerical value.

objA = {“color”:”Caf\u00e9″, “price”:164900.00};

Here the object ‘objA’ has got two properties ‘color’ and ‘price’.

 

Similarly we can define an object with multiple properties:

objA = {

“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”}

]

};

Since data layer is a javascript array and an array can contain one or more objects, we can have a data layer like the one below:

 dataLayer=[ {

“color”:”Caf\u00e9″,

“price”:164900.00,

“sizeList”:””,

“visitorsHasOrders”:true,

“data”:[45,67,89,20],

“shoppingCart”:[[“Clasicos”,57],[“Zapatos”,456]],

“pageAttributes”:{“page”:”product”},

“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”}

]

}];

Congratulations, you have just created your first complex data layer. 

Note: The data layer can become even more complicated when it contains server side script.

For example, here is how a data layer with server side script may look like:

datalayer with server side script

 

Quick announcement about my new book:

book look inside2

 

Read first few chapters of this book for free here.

This book is not very far from becoming Amazon Best Seller

amazon best seller

Click here to read first few chapters of this book for free.

 

Why do you need a data layer?

In the context of Google Tag Manager, data layers are used to collect data from a website.

GTM (aka container tag) can also directly pull data from the HTML of a web page by traversing the HTML DOM (structure of HTML) using JavaScript:

container tag data layer

By default a container tag pulls data from the HTML of a web page and push it into your analytics and marketing tags.

Now the problem with this approach is that the structure of HTML (HTML DOM) can change any time without your knowledge as commercial websites update all the time and any tag can stop working any day, any time without any prior notice.

To fix the problem we create and use data layers which stores all the information we want to collect about a web page. Once you set up a data layer, the container tag pulls data from the data layer of the page instead of its HTML

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).

 

Data Layer vs DOM Scraping

Each tag management solution (TMS) provider implement data layer in a slightly different way. 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 need to be hard coded on a website by your developer or IT team. So as long as you are using data layers, you 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 handy when it is not possible to implement the required data layers in a reasonable amount of time in order to set up certain tracking. Through DOM scraping you can implement TMS solutions faster, as there is little to no dependence on IT and you have more control over the implementation.

However TMS solution implemented through DOM scraping is not a stable solution, as changes in the HTML DOM (like change in the ID of a 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 lot of money is at stake (like airline websites).

 

What are data layer variables?

These are the variables used in data layer. It is in the format: ‘key-value’.

For example, in the data layer:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’,

’event’:’customizeCart’

}];

</script>

PageCategory, visitorType and event are data layer variables. As you can see they are basically properties of an object.

‘Statisitcs’, ‘High Value’ and ‘customizeCart’ are the values of PageCategory, visitorType and event data layer variables.

Note: Data layer variables are also known as data layer messages.

 

How you can initialize a data layer?

By setting up variables in your data layer. For example:

<script>

dataLayer = [{

‘pageCategory’: ‘Statistics’,

‘visitorType’: ‘high-value’,

’event’:’customizeCart’

}];

</script>

 

Appending/passing messages onto the data layer queue => Adding data layer variables to the data layer.

Updating data layer => adding/updating data layer variables.

Pushing information into the data layer => adding data layer variables to the data layer.

 

How information is pushed into a data layer?

If the data layer has been hard coded on a web page then certain piece of information is already available in the data layer. The other information can be pushed dynamically through the ‘push’ method of dataLayer object.

Through the ‘push’ method of dataLayer object you can dynamically add object(s) to your data layer.

The pushed object can contain one or more data layer variables.

For example let us suppose following data layer is hard coded on a web page:

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’}];

</script>

If you used the following push method:

<script>

dataLayer.push({‘visitorType’: ‘high-value’});

</script>

The data layer will now look like this:

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’}];

</script>

You can also push/add multiple variables at once into the data layer. For example:

<script>

dataLayer.push({‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’});

</script>

 

What should be the format of the information you push into a data layer?

The information that you push into a data layer from either 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 which are not recognized/recommended by GTM, then your ecommerce tracking won’t work.

<script>

dataLayer = [{

‘Transaction Id’: ‘1234’,

.

.

.

}]

}];

</script>

Here GTM won’t recognize ‘Transaction Id’ as ecommerce data layer variable.

The correct data layer snippet would be:

<script>

dataLayer = [{

‘transactionId’: ‘1234’,

.

.

.

}]

}];

</script>

Note: ‘transactionId’ is an example of identifier (as explained above). So it carries a special meaning and can’t be used as a regular variable name while using GTM.

 

How you can overwrite the value of 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:

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’}];

</script>

Now if you used the push method like the one below:

<script>

dataLayer.push({‘pageCategory’: ‘Maths’});

</script>

The value of pageCategory data layer variable would be overwritten and now your data layer would like the one below:

<script>

dataLayer = [{‘pageCategory’: ‘Maths’,’visitorType’: ‘high-value’}];

</script>

 

Naming convention for data layer variables

You should use a consistent naming convention for data layer variables.

If you use different variable names for the same variables on different pages, GTM will be not be able to fire tags in all the desired locations.

For example,

If you set up the page category on the signup page to ‘pageCategory’, then page category on a product purchase page should also be ‘pageCategory’ and not something like Pagecategory or PageCategory. This is because data layer variable names are case sensitive.

So following set up won’t work the way you think it should:

// signup page:

dataLayer.push({‘pageCategory’: ‘members-signup’});

// Product purchase Page:

dataLayer.push({‘PageCategory’: ‘product-purchase’});

But following set up will work the way it should:

// signup page:

dataLayer.push({‘pageCategory’: ‘members-signup’});

// Product purchase Page:

dataLayer.push({‘pageCategory’: ‘product-purchase’});

 

Data layer Variable names should be enclosed in quotes

dataLayer.push({pageCategory: ‘members-signup’});    // Won’t work

dataLayer.push({pageCategory: ‘members-signup’});    // works

 

The Data Layer javascript array itself is case-sensitive

so dataLayer is different from datalayer and the use of latter won’t work. For example:

datalayer.push({‘pagecategory’: ‘members-signup’});    // Won’t work

dataLayer.push({‘pageCategory’: ‘members-signup’});    // works

 

What is ‘event’ data layer variable?

It is a special data layer variable that is used with JavaScript event listeners.

It is used to fire a tag when a user interacts with webpage elements such as a forms, button, links etc.

Syntax for setting up an event:

dataLayer.push({‘event’: ‘event_name’});

Here ‘event’ and ‘event name’ are strings.

For example following code update the data layer’s ‘event’ variable when a user clicks on the button:

<a href=”https://www.optimizesmart.com/download” name=”pdfDownload” onclick=”dataLayer.push({‘event’: ‘pdf-download’});” >PDF download</a>

 

Can each web page has its own unique data layer?

yes and it should.

Do you need to put the same set of variables in the data layer on every page?

No.

When a data layer is updated in case of a tracked event?

When certain tracked event occurs like mouse click, form submission, page load etc.

 

What are dynamic data layer variables?

Data layer variables which are pushed dynamically to the data layer.

Syntax for setting up dynamic data layer variables

dataLayer.push({‘variable_name’: ‘variable_value’});

For example let us suppose following data layer is hard coded on a web page:

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’}];

</script>

If you used the following push method:

<script>

dataLayer.push({‘visitorType’: ‘high-value’});

</script>

The data layer will now look like this:

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’}];

</script>

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.

Note: Dynamic data layer variables are not hard coded on a web page.

 

How you can rename a data layer (or data layer object)?

The default name of data layer (or data layer object) is ‘dataLayer’. By making a small change in your container code snippet you can rename your data layer:

<!– 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>

<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’,’myNewName‘,’GTM-XXXX’);</script>

<!– End Google Tag Manager –>

For example:

<body>

<script>

 SmartDataLayer= [{

‘pageCategory’: ‘signup’,

‘visitorType’: ‘high-value’

}];

</script>

<!– 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>

<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 –>

 

<a href=”https://www.optimizesmart.com/download” name=”pdfDownload” onclick=”SmartDataLayer.push({‘event’: ‘pdf-download’});” >PDF download</a>

 

When you need to rename your data layer?

When you are using multiple container codes on a same web page and you don’t want each container to use same data layer.

For example:

<body>

<script>

dataLayer1 = [{

‘pageCategory1’: ‘signup’,

‘visitorType1’: ‘high-value’

}];

</script>

 

<!– Google Tag Manager  Container-1–>

<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’,’dataLayer1‘,’GTM-XXXX’);</script>

<!– End Google Tag Manager Container-2 –>

===================================================================

<script>

dataLayer2 = [{

‘pageCategory2’: ‘signup’,

‘visitorType2’: ‘high-value’

}];

</script>

 

<!– Google Tag Manager Container -2 –>

<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’,’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 –>

===================================================================

<a href=”https://www.optimizesmart.com/download1″ name=”pdfDownload1″ onclick=”dataLayer1.push({‘event’: ‘pdf-download1’});” >PDF download 1</a>

<a href=”https://www.optimizesmart.com/download2″ name=”pdfDownload2″ onclick=”dataLayer2.push({‘event’: ‘pdf-download2’});” >PDF download 2</a>

<a href=”https://www.optimizesmart.com/download3″ name=”pdfDownload3″ onclick=”dataLayer3.push({‘event’: ‘pdf-download3’});” >PDF download 3</a>

Note: By default, each container will use a common data layer.

 

Do you need to be a web developer in order to use data layer?

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.

When do you really need a web developer to write data layers for you?

When you have to create complex data layers like the one which pull information (like ecommerce data) from the back-end (server side) and convert that information into a format, which GTM can understand.

 

What is data layer snippet?

It is the data layer enclosed within <script> ….</script> tag.

Following is an example of data layer snippet

<script>

dataLayer = [{‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’}];

</script>

 

What is container tag snippet?

It is the code which is used to create a new container tag. A container tag holds all the marketing/analytics tags, triggers and variables for your website.

When you are installing Google Tag Manager on your website, you are basically installing a container tag. 

Following is an example of container tag snippet:

<!– 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>

<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 each and every web page of your website.

 

Where the data layer snippet should be placed?

It should always be placed above your container tag snippet. For example:

<script>

  dataLayer = [{‘pageCategory’: ‘Statistics’,’visitorType’: ‘high-value’}];

</script>

<!– 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>

<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 –>

 

Why the data layer snippet must be placed above the container snippet?

So that data layer variables are available to the container.

If you place the data layer snippet below the container snippet then the data layer variables won’t be available to the container. In other words, the container tag won’t be able to pull data from the data layer.

For example following set up will 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’ won’t be available to the container as the data layer code has been placed after the container snippet.

 

When Google Tag Manager functions best?

when used alongside a data layer. You must have know it, by now.

Is it mandatory to declare data layer?

No. Explicitly declaring a data layer is optional.

Can you use GTM without explicitly implementing data layer?

Yes. In that case GTM container code will automatically create its own data layer object for you.

 

Do you need a container tag to implement a data layer?

As long as you are using Google Tag Manager, you need a container tag to implement data layer otherwise not.

You can create a javascript array which store all the information you want to collect about a page and use it as a data layer.

For example:

<script>

mydataLayer = [{

“pageCategory”: “Statistics”,

“visitorType”: “high-value”

}];

</script>

 

How you can selectively fire tags on page load?

through GTM triggers.

What is the downside of not using data layer?

you cannot use events without data layer and above all your whole GTM implementation will be pretty shaky.

How you can access values from a page without implementing data layer?

By using custom variables.

 

How you can implement data layer on a web page?

by adding following snippet of code above the container tag snippet:

<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:

<script>

dataLayer = [{‘pageCategory’: ‘Maths’,’visitorType’: ‘high-value’}];

</script>

 

What is the scope of data layer variables?

Data layer variables are page specific. That means they exist as long as a user remains on the same page.

How you can declare data layer variables that are relevant across pages?

By using the same variable name on multiple pages of your website.

 

What information you should store in a data layer?

This is the most important question of all.

If you want to avoid the hassle of modifying data layers every time you deploy a new TMS solution then you should aim to hard code one separate data layer on each web page of your website.

Each 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

#2 Product 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)
  • product availability (available, out of stock)
  • product coupon
  • product coupon used

#3 Logged-in and Logged-out Users attributes – user type (like high value repeat customer), user id, browsing behavior, preference, purchase history etc.

#4 Tracked Users’ interactions – clicking a button, submitting forms, signups, purchase, watching videos etc.

#5. Any information that might be useful in the near future for additional tracking.

Following is 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 how this data layer looks like in Google developers tool’s console tab:

data layer example

If you look 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. So that debugging data layer becomes easy later.

Another thing worth noting is that the data layer contains some dynamic data layer variables near the end: 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 see and interpret the data layer on a web page?

Tweet to read the step by step method of interpreting data layer on a web page.

To do this, follow the steps below:

Step-1: In Google Chrome, right click on a web page (the page must have the GTM container tag installed) and then select ‘Inspect Element’. This will open up the developers’ tool window at the bottom of your browser.

Step-2: Click on the ‘console’ tab at the top right of the tool window and then type ‘dataLayer’ at the command prompt and press ‘enter’ key:

type data layer at the prompt

Once you press the enter key, you will see following 3 default JavaScript event objects:

javascript objects

here,

gtm.js is a javascript library file used by the container tag. If this library file doesn’t load then your GTM won’t work. Once 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 then 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 then it means, 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 get these three events from the container tag.

If your data layer doesn’t get any/all of these events then it means something has gone wrong with your tag manager implementation.

It could either be a broken container tag or broken data layer or both.

If you have hard coded data layer on a page then developers’ tool window will show you at least 4 JavaScript objects.

One JavaScript object would be your data layer and the other 3 will be the default JavaScript event objects:

javascript objects 2

 

 

Other article you will find useful: Bare Minimum Statistics for Web Analytics


Quick announcement about my new book on Web Analytics and Conversion Optimization

The role of maths and statistics in the world of web analytics is not clear to many marketers and web analysts. Not many talk or write about the usage of statistics and data science in conversion optimization. That is why I have written this book Maths and Stats for Web Analytics and Conversion Optimization to fill this knowledge gap.

This expert guide will teach you, how to leverage the knowledge of maths and statistics in order to accurately interpret the web analytics data and take business and marketing decisions which can quickly improve the bottom-line of your online business. Read first few chapters of this book for free here.


 

Himanshu Sharma

Certified web analyst and founder of OptimizeSmart.com

My name is Himanshu Sharma and I help businesses in finding and fixing their Google Analytics and conversion issues.
  • More than ten years' experience in SEO, PPC and web analytics
  • Certified web analyst (master level) from MarketMotive.com
  • Google Analytics certified
  • Google AdWords certified
  • Nominated for Digital Analytics Association Award for Excellence
  • Bachelors degree in Internet Science
  • Founder of OptimizeSmart.com and EventEducation.com
I am also the author of the book Maths and Stats for Web Analytics and Conversion Optimization If you have any questions or comments please contact me