193
The Little Book of GTM Best Practices Doug Hall ConversionWorks 1

The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The Little Book of GTM Best Practices

Doug Hall ConversionWorks

!1

Page 2: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!2

Page 3: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction 5

Section 1 - Planning 8 Chapter 1 :System design and measurement planning 9

Section 2 - Implementation 31 Chapter 2: Implementation conventions 32 Chapter 3: Container script considerations 42 Chapter 4: Reliable dataLayer implementation 50

Section 3 - Conversions 59 Chapter 5: Page level data measurement 60 Chapter 6: Tracking clicks 78 Chapter 7: Advanced user interaction tracking 95 Chapter 8: Form data capture best practices 113 Chapter 9: e-Commerce tracking 123 Chapter 10: Social 131 Chapter 11: Onsite search 137 Chapter 12: Tracking engagement 152

Section 4 - Operations 158 Chapter 13: Development and debugging 159 Chapter 14: Administration and configuration 176

Section 5 - Conclusion and next steps 189 Conclusion…or is it? 190 Suggested further reading 191 About the author 192 About ConversionWorks 193

!3

Page 4: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!4

Page 5: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Whilst the concept of tag management is not new, the growth of online marketing, analytics and optimisation has heralded a proliferation of tag usage on websites. This has brought tag management to the forefront of of the business agenda with analytics budgets outstripping spending on other areas in IT 1

Launched on October 1, 2012, the pace of development of Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate of change in complex software products is a reflection of how tag management systems have made an impact on web site owners, marketers and technologists.

The value and appeal of a product specific manual is very limiting so this book is not a GTM manual. GTM moves way too fast for a worthwhile manual to be written and considered up-to-date. Use the online documentation for the nuts and bolts. To get the most from this book, read it as a guide to getting the most out of your TMS for the minimum time invested.

This book will encourage and help you to spend less time building and maintaining your tag management solution so you can spend more time extracting insights and value from your data. You'll do this by using the design patterns and best practices explained and demonstrated in these pages.

Dan Vesset, Ashish Nadkami, “Worldwide Business Analytics and Service 1

2013-2017 Forecast IDC Report Dec 2013!5

Page 6: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Use these techniques through all the stages of your project, from design to build and debug, through to deployment, management and maintenance. Whether you’re using the TMS to manage your marketing tags or Google Analytics, the quality of the technical solution will be improved. The aims of this book are to give the reader:

- Reduced development, testing and maintenance effort - Improved data quality - Improved system design - Awareness of measurement anti-patterns to avoid - Deeper GTM and GA knowledge

Website optimisation and online business growth requires the capture and analysis of well designed, high quality data. Decisions and actions are based on insights extracted from the data so you need to trust and have confidence in the data.

What if we don’t have well designed and good quality data? Basing business decisions on sub-standard data is potentially more dangerous than not using data to help with decision making at all.

Delivering high quality and trustworthy data need not be a lengthy or expensive exercise though.

Take click tracking for example: Click tracking seems as if it should be ‘bread and butter’ to site owners and developers. It can be the easiest recipe in digital analytics. However, frequently the importance of measuring a click is so intuitive and instinctive to the site owner that they assume developers know this too.

!6

Page 7: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Failing to communicate the importance of measuring specific user interactions means that site owners are unwittingly reliant on the developers’ clairvoyant skills rather than their technical abilities. The all-too-frequent end result is the implementation of beautiful looking features that are implemented in such a way that, at worst, they are unmeasurable and at best, they are hard and expensive to refactor for effective measurement.

This is a key lesson in communication and is equally applicable to business and technical people. We're all guilty to some degree of poor communication:

Tell me, and I will forget. Show me, and I may remember. Involve me, and I will understand. (Confucius, BC 450)

Having picked up this book, having scanned this introduction, you recognise you need to use a Tag Management Solution and you want to use it well. You need to avoid common pitfalls or it could cost rather than deliver value.

The book is organised to follow the flow of a typical project from inception, design and planning, through design and build to operational procedures and onwards. You'll see how to avoid anti-patterns, pitfalls and potential mistakes at all stages in the project lifecycle.

!7

Page 8: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Section 1 - Planning

This section covers the things you need to do before you start your project. It'll save time, money, pain and regret in the long term. Avoid physical and mental short cuts even though there will be temptations that suggest you might save a day here and there on a project or feature. You might be tempted to just get this form working and deal with some measurement refactoring later but what if that form is the form – the one that delivers all the value on the site? You want to get that form built and measured right but not at the cost of design, branding or functionality.

Let's see how you can do this.

!8

Page 9: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 1 :System design and measurement planning

Summary

A poorly considered system design can bake anti-patterns into your solution very easily. Parents will attest to the value in making sure children don’t pick up bad habits from an early age. Similarly, ensuring your solution doesn’t have flaws designed into it from the start is crucial to success.

Treating digital analytics measurement as an architectural layer in the system is a pattern to employ in the design process.

Good technical architects will give careful consideration to the data, business logic and presentation layers in the system design process. Equally, applying thought to the measurement layer leads to a better and more robust architecture.

Thinking about the measurement of a site, a test or even just a new feature as part of the design and build process encourages you to think early about what data to capture so as to prepare the ideal technical solution for the instrumentation:

!9

Page 10: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-pattern - treating web analytics as a last minute annoyance Anti-pattern - failing to think beyond pageviews Anti-pattern - not focussing on data quality Anti-pattern - misuse of the measurement layer - fixing a site with tracking pixels

Give careful consideration to system design - Adopt data design into system design - Design and build to be measured - Data exhaust is relevant to all systems - Consider who to involve in the system design process

!10

Page 11: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design and Planning

Talking about system design at the start of this book is no accident. Whether your current system design process is iterative or linear, at some point you will address the logical system design and the physical system design. You need to include measurement considerations in this process.

The logical system design examines the data flow through the user interface to the business logic layer, the database layer and back to the user.

Think and plan what user behaviour you want and need to record. How you will do this and why you are capturing this data is dealt with later. Focus on the what initially - you can tune and refine this later if need be. Include monitoring and diagnostics data capture at this point. As you plan how to capture user behaviour data, include failure modes and how they will be tracked in addition to the measurement of correct functionality. We’ll discuss specific use cases for failure mode tracking later.

This phase of the process is focussed on scrutinising the flow of data from the core system to other connected systems. The measurement layer will receive the same degree of attention at the design phase as a CRM or billing system does. Notice there is no fundamental change to the system design process but a failure to expand your situational awareness to include

!11

Measurement design is a fundamental part of the overall system design

Page 12: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

all inter-system dependencies is where this process often falls down.

The physical system design will focus your attention on the format of data flow into and out of the system. Take a step back from the detail and treat the whole system as a black box for now. Think purely about the nature of the input and output as this will help concentrate your attention on the user interface.

How users engage with the front end is the crux of the measurement challenge. Think about how you extract behavioural data points and what you will use them for. Having considered what data to capture in the logical system design phase, now you need to think about how to capture this data.

The logical system design (what data you want to capture) is a key input to the physical system design process but you will not accomplish this alone.

The process of designing a web front end is an evolving science. As internet usage grows and changes, the set of topics to deal with mirrors the changing landscape. Try searching on Google for ‘things to consider when designing a website’. You’ll find a rich seam of helpful articles that cover myriad subjects including but not limited to those listed below:

!12

Page 13: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

- User Experience - functionality & navigation - Aesthetics/design - branding - Privacy & Security - Organic search performance - Measurement - Multi device capabilities - Accessibility - Cross browser capabilities - Speed & page weight - Maintainability

This list is presented in descending order of frequency of occurrence based on a less-than-scientific study to illustrate this point.

They all matter and they all affect each other. Crucially, the people responsible for each area are also affected and dependent on each other. Capitalise on this by ensuring the team relationships and team dynamic reflect this situation.

All individuals responsible for the site need to talk, interact, share, collaborate, support, innovate and deliver together to complete the system design.

!13

Measurement does get attention and thought but the key issue is a lack of recognition that these subjects are all

intricately linked and dependent on each other.

Page 14: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Include the right people in the design process

Who do you need to include in the system design process to ensure all relevant stakeholders contribute to a cohesive solution?

Based on the opening section in this chapter we are aware of the subjects involved in the system design:

- User Experience - functionality & navigation - Aesthetics/design - branding - Security & Privacy - Organic search - Measurement - Multi device - Accessibility - Cross browser - Speed & page weight - Maintainability

With respect to these areas of interest, start by considering these questions:

- Who has ultimate responsibility for the website? - Who needs tags (data) and why? - Who builds the tags? - Who publishes the tags? - Who designs the website? - Who builds the website? - Who tests the implementation? - Who maintains the site?

!14

Page 15: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

- Who is responsible for the strategic alignment of branding, functionality and measurement with respect to the organisational goals and KPIs?

The groups of individuals identified by these questions can be categorised by their areas of expertise, the design aspects that they can influence and their key responsibilities.

Get these people in a room before any decisions are made:

Area of expertise/influence Stakeholder

User Experience - functionality & navigation

Designers

Aesthetics/design - branding Marketing Branding Designers

Security & Privacy IT/Ops

Organic search Marketing SEO

Measurement Analysts

Multi device Developers Ops/IT

Accessibility Designers, testers

Cross browser Developers Designers Testers

Speed & page weight Developers Testers

Maintainability Developers Ops/IT

Strategic and tactical alignment CxO (Marketing, Operations, Technology)

!15

Page 16: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

All stakeholders in the design process have a responsibility to be aware of, acknowledge and respect the other aspects of the system design. To ensure the ownership of the system design is shared, it’s fundamental to include all stakeholders in the design process.

The format of the output from the design process is unlikely to be radically different to what you currently have. However, the content may be very different. The quality of the design will be improved because you will have a shared vision of the solution. You will have a consensus that will satisfy all requirements. You may initially take longer to produce the best system design by involving the full suite of stakeholders but over time as each stakeholder learns what requirements are important to other stakeholders, the process becomes easier, quicker and better.

We’re now going to swallow the metaphorical red pill and 2

understand how and why we include measurement in the system design. The scenario described below is a fictional tale of woe caused by a failure to involve the right people in the process.

A Bad Day: The office HiPPO decides the homepage needs a new 3

carousel, has a chat with the design team and gets the project rolling. Everything seems fine.

http://en.wikipedia.org/wiki/Red_pill_and_blue_pill2

Avinash Kaushik - http://www.kaushik.net3

!16

Page 17: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The design team present what they think is the best design based on the brief to the developers who build the carousel using Flash and javascript.

The bounce rate on the homepage goes through the roof and conversions hit the floor. The HiPPO wants to know why!

The analysts sigh as no data is captured so they can’t explain the issues using conventional analytics techniques. The SEO guy feels that his day has been ruined because the new carousel doesn't have any h2 elements…

Nobody can answer the question. More expensive development, testing, analysis and reporting is required. The cost of the new carousel has tripled and the ROI has evaporated.

A lack of thought and communication has resulted in political warfare in the office and a homepage feature that is not measured or built properly. The business has suffered needlessly. This situation is common and totally avoidable.

!17

Page 18: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-pattern - treating analytics as a last minute annoyance

The common problem: There is a pressing deadline. There is a shortfall in the project budget. Resource is scarce and the site has to go live on time. The snag list seems to grow by the hour and decisions need to be made. Maybe cutting corners is an option now? This is a common reality and this is not an easy prioritisation exercise.

It’s all too common to take an easy option such as ditching Google Analytics for the first roll out. All that javascript is extra weight and complexity that can be retrofitted later, right?

The 'meh' is a feeling of ennui towards measurement as it is perceived to add little to the solution other than weight and complexity which is unwelcome on a tight schedule. What’s the point in measuring a site if the site is not live?

This is true but only up to a point. You can safely retro-fit analytics but only if you’ve thought through the site measurement at the physical design stage. You need to have a solution design that has been designed to be measured even if the measurement is not yet implemented.

Good quality markup is the key At the heart of the user interface is the markup - the HTML, CSS and JavaScript that makes up the pages. The quality of the markup will dictate whether you can legitimately delay

!18

Avoid the 'meh'

Page 19: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

implementing instrumentation. The markup will also have a huge bearing on the expense and risk in moving digital analytics vendor if you choose to switch in the future. Get your markup built well and and you'll have a measurable site that will work well with most digital analytics systems.

Risking a highly tenuous comparison, there are a number of parallels between sayings in sport and relevant interpretations in website measurement:

Sport Measurement

You’re only as good as your last result. Your measurements are only going to be as good as the markup used on the site.

The more you practice, the luckier you get.

Thinking about measurement up front is essential to success

Pain is only temporary but victory is forever.

Thinking about measurement up front, no matter how hard it seems, is essential to success - it’ll be worth the effort.

If you fail to prepare, you're prepared to fail.

Not giving thought to measurement during the design process increases the prospect of failure

!19

Page 20: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

You will recall the list of topics to consider in the design process earlier:

- User Experience - functionality & navigation - Aesthetics/design - branding - Security & Privacy - Organic search - Measurement - Multi device - Accessibility - Cross browser - Speed & page weight - Maintainability

The inextricable linkage between these subjects is not that they are all relevant to the site front-end (of course they are), it’s the domino effect each has on the others.

For this discussion we’ll assume that the design artwork has been agreed and signed off, the functionality is specified clearly and is set in stone. The security of the site has to be assured - this is not a mutable point. We’ll also assume that the multi-device, cross browser and accessibility aspects are a given - they have to happen and are part of the design and functional specification. This leaves the following:

- Measurement - Organic Search - Speed & weight - Maintainability

These site properties cannot dictate or influence the aesthetics or behaviour of the site in anyway - the users'

!20

Page 21: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

experience comes first. This quartet of facets are ideal BFFs 4

as they are potentially massively beneficial to each other and are all totally dependant on the markup quality. The utopian goal is getting the markup designed to cater for all of these topics. In doing so, all aspects will be mutually complimentary.

Well designed markup will work well in terms of organic search performance. It will be lightweight and easy to maintain delivering fast loading pages that are semantically rich in content and meta-data and therefore supportive rather than obstructive to measurement.

Anti-pattern - failing to think beyond the pageviews

You’ve fully subscribed to the idea of building measurement into the system design process. Great. Now, make sure the measurement coverage is as full and complete as possible. During the logical system design, when you think about what to measure, make sure you consider what user interactions are important to your site.

The scope of website measurements extends beyond basic pageviews – it extends as far as your imagination and the scope of your site and your business will allow. Examine the broad picture of the site, the navigation, all the domains used on the web property (not forgetting mobile domains, secure domains and micro-site domains), on page functionality, off page functionality (consider offline data capture too) and most importantly what the desired outcomes are on the site and what they mean to your business.

"Urban Dictionary: bff." 2003. 16 Apr. 2014 http://www.urbandictionary.com/4

define.php?term=bff!21

Page 22: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The strategic and tactical goals of the site (what you want your users to do on the site and why) will form the key performance indicators on which you’ll base your definition of success. The process of defining key performance indicators from strategic and tactical goals has been well covered in other textbooks so I’m not going to labour the point here.

Instrumenting the site and the business is not a journey of a single step. Accept the reality that the site will evolve. You’ll embark on testing programmes which inevitably result in change. You will not be able to anticipate all the potential measurements you’ll ever need at this point but designing and building with measurement in mind at all times will serve you well and deliver strong returns.

The point is to avoid the trap of not thinking beyond the pageview metric. Setting up the most basic boilerplate instrumentation is not a robust, long term solution. Failure to plan your digital analytics evolution with sufficient scope and clarity will lead you into the next anti-pattern.

!22

Just because something is easy to measure doesn't mean it's important:

Seth Godin

Page 23: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-pattern - focusing on data volume rather than data quality

Beware the temptation to measure everything and anything. Just because you can measure something does not mean it needs to be measured. Think about why the CXO is included in the system design phase. They’re present to help make sure the right things are measured.

Data quality is king – not data volume. Where standard metrics are available in Google Analytics, use them. If every click seems to be important, ask what business question is being answered by measuring them? Will knowing about every click as an event provide insight into customer behaviour? Is GA even the right tool to capture this data? Widespread click measurement is often best served by a dedicated tool such as Mouseflow, HotJar or ClickTale.

Effective data capture refers not only to the elegance of the technical solution but also to the elegance and fitness of the data that is captured. Doing more with less is not the required mindset though, do more with better.

Don’t drown in data. Data is the nourishment for your appetite for insight. Analysis needs to be revealing and valuable rather than onerous and costly. Let the data help you make decisions but don’t let it take over.

!23

The strategic alignment and relevance of the data exhaust is more valuable than being able to record every click of every link using an event.

Page 24: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Designing your data exhaust to be simple and beautiful rather than massive and clumsy will deliver tangible returns.

Anti-pattern - fixing the site with the measurement layer

Baking in the anti-patterns described so far will have an unavoidable knock-on effect. You know you’re going to have to retrofit the measurements and you’ll find that the markup doesn’t easily and robustly support certain tracking techniques. You may find that multiple forms are submitting to the same URL, you’ve encountered a requirement for a new metric that is impossible to track currently or that the pageview data is rubbish as it’s all /index.aspx?documentid=abc123.

What now?

‘What now’ is pain and tears and cost. Of that there is no doubt. But you can rejoice as a mirage appears on the horizon. It manifests as an easy route to salvation. This tempting apparition makes you think you can ‘fix-up’ the site without having to initiate a major refactoring exercise.

!24

Apple never designed the iPad. They undesigned the tablet. They focused on creating the simplest form possible. Every single decision is based on usability, readability, comfort, and focusing your eyes on the content itself.

It is beauty through simplicity.

Page 25: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This corrupting influence is the prospect of flexing your scripting, GA and GTM muscles rather than addressing the underlying site issues.

Avoid using these hacks:

Forms with 1 URL Here’s an easy fix - when the form is posted, just drop a value in the dataLayer to flag the form as having posted to an appropriate virtual pageview for use in a goal. N.B – this is quite a different beast to the AJAX form that will be discussed later.

index.aspx?documentid=abc123 A great example for a lookup table. Use the ID from the querystring parameter to set the virtual pageview - simplicity itself!

Multiple outcomes reported on one URL Users can choose to sign up for a newsletter, request a quote, buy a widget or submit a ‘contact-us’ form which all finish on thankyou.php

You only need to pop a dataLayer variable on the thankyou.php page to flag which outcome is which and you’ve nailed the tracking solution.

!25

Page 26: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Don’t try this at home… There were some pretty tempting 'get out of jail' tricks there but here’s why these common practice hacks are not best practice.

Forms with 1 URL will not scale because: Every time you add a form you need to do extra work. The fundamental issue here is that under the hood in the source code, a controller is returning content to the presentation layer without updating the URL in the response. This is lazy and highly wasteful. This solution will not scale.

index.aspx?documentid=abc123 is a failure because: Fixing up the measurement for you is selfish when you’re leaving analysts, search engine bots and users with the awful URLs your system spits out.

Fix the URLs to be meaningful to machines and humans and you’ll offer a better user experience. Maybe you’ll find some better organic search performance? Analysts will be able to use the inPage analytics reports and will be able to link from reports to the pages.

I certainly wouldn’t want to be the one to manage your virtual pageview lookup table…another difficult to scale solution that is also not aligned with organic search performance goals.

Multiple outcomes reported on one URL are harmful to measurement because: You’re not thinking beyond the pageview! Consider the tracking of other actions on the thankyou page - if you have 4 outcomes all finishing on the same URL, you have 4 pages

!26

Page 27: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

with the same URL. You have thankyou.php but you should have

- thankyou-newsletter-signup.php - thankyou-contact-us.php - thankyou-sale.php - thankyou-signup.php

Think about measuring clicks on these four, logically different outcome pages. If you use the same page, you use the same URL, the same markup – everything. This means you can't identify any other clicks or user interactions on these pages without reference to the page referrer – which may not be reliable and is another unnecessary chunk of complexity.

Make the GA goal definition easier and better. Implement the outcomes on different pages. You’ll have more pages on the site to maintain but the tracking is easier and the pages can then be optimised in isolation.

Occasionally, fixing up a site using the measurement layer and GTM is viable if only to demonstrate that the required fix works.

It is not a viable long term strategy.

Don’t use the measurement layer to make permanent hack-fixes to the site. This is poor software engineering and results in wide ranging long term issues - time, effort, cost and risk are all affected. Having said that, do use temporary proof-of-concept fixes to demonstrate what the long term solution will do. Just don’t leave them there. You’ll be tempted but be strong!

!27

Page 28: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design pattern

We’ve discussed the potential ramifications of adopting the anti-patterns described in this chapter, the root cause being choosing short term gains whilst failing to think ahead. The end results are painful:

- Technical fragility - Cost - Risk - Effort - Performance issues - Incomplete ROI

In isolation, the detrimental effects of these results can be assuaged with some effort. In combination with the incomplete ROI data, the compound impact of these effects are tangible, harmful and take considerable effort to alleviate.

With respect to these anti-patterns, the right approach to designing systems intelligently with future returns in mind leads us to some simple heuristics:

- Give careful consideration to measurement at the system design stage. Don’t leave it to the last minute.

- Include measurement design into system design. Identify the data you need to capture and build to be able to measure them.

- Design and build the system to be measured from the start and for the future. Cater for current and future measurement in the design.

!28

Page 29: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

- Data exhaust considerations are relevant to all systems and users. Think how feature usage and failure modes will be measured as the functionality is designed and built. Keep the data exhaust relevant - don’t drown in data - focus on data quality rather than quantity.

- Include all relevant stakeholders in the design process. Ensure decision makers are involved in key design choices.

From the earlier story, let’s see how applying these heuristics can turn a Bad Day into a Great Day:

Our HiPPO talks to a friendly competitor who sings the praises of the product carousel on their homepage and decides to commission the analysts to conduct a little research.

The analysts are tasked to conduct some voice of customer research. Additionally they look into 3rd party studies and dig into data regarding engagement on the current homepage.

The insights are shared with all stakeholders during the design process and it is collectively decided that the type of carousel suggested is unlikely to work well on their type of site as the data suggested the performance would be poor.

Using the data the business collectively decides to not take the risk of a poor performing homepage. So, the chosen feature design uses a conventional menu system with top level category pages instead of a carousel.

The designers happily deliver the visuals.

!29

Page 30: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The developers know that the menu system can be done with HTML and CSS and doesn’t need Flash or JavaScript. They are aware of the expected user behaviour and build the markup so that the key measurements are supported out of the box. The markup also supports extending the instrumentation in the future if required…

The SEO guy has his h2 elements in the right place on the page.

The key user interactions with the homepage are correctly measured and each stakeholder understands the reasoning behind the decision.

The chosen design gets tested. There is no observed impact on bounce rate, the data quantifies the ROI and voice of customer feedback confirms that users are delighted by the new feature.

The design is permanently implemented and conversion rates soar. The end results worked with the least investment and maximum return.

The moral to this tale is the value of investing time and effort in the design process is considerable. The time and effort spent at the design stage is not a cost - it’s an investment and an extremely valuable venture.

!30

Page 31: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Section 2 - Implementation

Your planning has been faultless. All your stakeholders are aligned and have contributed to the design. You're in a good place and ready to engage on your project.

Use this section to make sure the execution is as good as the plan and design promised.

!31

Page 32: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 2: Implementation conventions

Summary

Early in 2014 eConsultancy reported that Tag Management 5

System (TMS) adoption is set to reach 50% by 2017. Hindsight may reveal this estimate to be somewhat pessimistic if the growth of TMS adoption fails to abate.

Google Tag Manager adoption is flourishing for many reasons. A strong candidate accounting for the rapid growth of the tool is that it's very easy to start using.

The ease with which GTM can be picked up facilitates and encourages rapid delivery. Unfortunately, it’s very easy to become careless and sloppy when prototyping. The pace is high, experience is light and the tool is initially forgiving of loose discipline which often leads to unmaintainable solutions.

This need not be the case. A little extra care and thought up front will help deliver a prototype quickly that will easily refactor into a production ready solution.

This chapter describes a selection of key points that will help you get your GTM conventions right and still deliver solutions quickly.

https://econsultancy.com/press-releases/7388-tag-management-adoption-to-5

reach-50-by-2017!32

Page 33: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Write To Be Read: Use solid Naming Conventions

Having used GTM previously you may have found that over time the volume of assets can grow very quickly into a hard to manage mass of tracking stuff. The purpose of the assets becomes cloudy over time unless they are named logically and discipline is maintained.

Naming and carefully organising your assets will reduce the amount of effort needed for documentation, aid maintenance and asset reuse. Use the tool to organise your assets and support your naming convention. This will make life easier for you (whatever your role), developers, marketers and testers.

Easier means reduced risk, less time, less repetition and less money wasted on tagging. Yes, wasted. Remember that tagging does not have a direct impact on your bottom line in the same way as optimisation does. So, tag less (write less code) and move on quickly to something more important.

These 4 simple heuristics will guide your naming strategy.

Use existing conventions If you have existing naming conventions within your team, use them. The familiar naming scheme will help you find and manage your GTM assets. Naming scheme rules may include case and white-space usage, references to functional areas of the site and include business specific vocabulary. GTM is an extension of the site codebase and so needs to be subject to the same naming rules.

!33

Name and organise your GTM assets with readers in mind

Page 34: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Relate GTM assets Tags have the most specific use cases. Tag names need to reflect their usage, type and function as this will help group related assets.

Name tags according to their usage, type and function The convention used below is: Site area - Tag type - Tag function

Searching in a fictional GTM container for tags by their site function, looking for all the tags that are used on the home page by searching for ‘homepage’ yields the following tags:

- Homepage - GA Event - phone link click - Homepage - GA Event - see all phones button click

In the same GTM container we can find the tags that respond to clicks by searching for ‘click’:

- Product pages - GA Event - buy now click - Basket - GA Event - remove from basket click

Looking for all the AdWords tags in our made up container we find these three tags:

- AdWords - Sale Conversion - AdWords - Basket Remarketing - AdWords - Contact Us

!34

Use agreed naming conventions. Apply logic and avoid essays in your naming convention

Page 35: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

See how simple it can be to find the right tag for the measurement task in hand? Notice that the search is case insensitive but case adherence in names needs to be strictly maintained.

Name triggers according to their usage and function Triggers have more general use cases. They will be used by multiple tags and so the naming convention reflects this wider usage.

The convention used below is Site area - function

Using the same example GTM container, searching for ‘homepage’ lists all the triggers using the homepage in the logic:

- Homepage - phone link click - Homepage - See all phones button click

Searching by trigger function for all triggers that use a URL to fire tags, we find these assets:

- All pages - URL - Phone pages - URL - Contact page - URL - Basket page - URL - Transaction complete - URL

When building tags, the ability to find the right trigger quickly and easily aids the pace of development. Finding an existing, proven trigger that can be reused eliminates the need to build and test a new trigger - effort and testing time is reduced.

!35

Page 36: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Name variables according to the type and the data returned Variables are a key conduit between the presentation layer and GTM. They are used to transfer data from the page (presentation layer) to GTM (the measurement layer).

Variables will be the most widely used GTM asset so the naming convention will be the least specific in terms of not including a site area or function but the name must still clearly indicate the variable usage and ideally the data type returned. Be aware that custom JavaScript variables may return any type of data but the nature of the variable use may cast the returned value into a String.

Avoiding repetition of variables and ensuring their correct usage requires a clear naming convention. This will most probably be guided by your current development standards. The closer you can adhere to the standards used by your development team the better.

Referring back to the planning chapter, this is an illustration of the value of ensuring all stakeholders are involved in the system design - especially developers when naming conventions are the topic of discussion.

The GTM native variable type names are a solid starting point for this discussion.For example:

- 1st Party Cookie - Constant String - Data Layer Variable - URL

!36

Page 37: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

These variable types may well form part of the variable name. For example, being able to search for all the variables that return data pertaining to a URL or a dataLayer variable is highly beneficial.

Searching for variables that return specific DOM element attributes facilitates auto event tracking. You will need to extract an element id or class often using built in variables.

This is by no means intended to be an exhaustive list of tag, trigger and variable naming schemes. Feel free to tune, tweak and grow your own conventions but make sure they are used rigorously.

Peer reviews Consider this little adage when building your GTM implementation:

Tell me, and I will forget. Show me, and I may remember. Involve me, and I will understand. (Confucius, BC 450)

Use your peers to review your work (and vice versa). Learn from each other. Make each other aware of changes, ideas, plans or issues and involve the team to build a shared understanding of your GTM system.

!37

Page 38: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Useful comments - not essays If you find yourself in this situation you need to have a careful think about your commenting practices:

! Use notes, version names and comments to your advantage by relating version numbers, names and comments to sprints.

!38

Use notes, version names and comments to help GTM audits

Page 39: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The Best Code is No Code: Coding Conventions

It's an old adage that the best software has little or no code. 6

Adding code adds complexity, risk, time and expense.

In the context of GTM this means avoiding unnecessary use of custom JavaScript where native GTM functionality can be used.

A scenario that is often encountered that leads to the temptation of jQuery is the use of return false, stopPropagation or cancelBubble rather than preventDefault.

When DOM elements are clicked, you may want to track the click event. Placing the event handler on the body element, click events on child elements will bubble up to the body element where GTM can natively handle the event as you desire.

Unless…

The developer may need to change the behaviour of the clicked element. For example, a validation error on a form field may need to be handled without submitting the form.

The developer may choose stop the form submitting using return false or in some circumstances cancelBubble or stopPropagation. These techniques will stop the event from

http://blog.codinghorror.com/the-best-code-is-no-code-at-all/6

!39

Less custom Javascript and HTML = better

Page 40: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

bubbling up to the body element and GTM will not be able to handle the click event.

Attaching a custom JavaScript event handler to the clicked element, perhaps using jQuery or a similar framework is actually quite simple and quick to do but the short term gain may lead to long term cost. This code will need to be maintained and potentially copied and reused in other similar cases.

If the preventDefault practice was used instead, the event will be allowed to bubble up and native GTM click event handling can be used. The standard GTM solution is a form filling exercise.

Which technique is correct? You need to weigh up the costs and benefits within your team with respect to your particular project and solution. The ideal scenario is the one where all stakeholders agree and know what decision has been made and why. Aim for efficiency in your software but also be pragmatic about the solution. You will often be faced with a choice between expending reasonable effort to produce the best markup or seemingly less effort to write some custom JavaScript instead where there are longer term costs to consider. Avoiding long term pain where possible is advisable but ultimately you need to make an informed decision and be aware of the consequences,.

!40

Page 41: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Consider this hypothetical question from a fictional client:

"Should we calculate the value of a transaction including a discount in a variable? It seems cool, quick and easy to do this in GTM…”

Yes, it does seem cool, quick and easy, but it's quite wrong. Don't build business logic into the measurement layer. Discounts and offers are hard to model well and robustly in software. Complex business logic needs to reside only in the software that governs it. Avoid unnecessary repetition of complexity in the measurement layer.

Treat GTM as an architectural layer in your software system. Ask the measurement layer to do measurement things not business data operations or presentation operations. Respect the separate responsibilities of the system components.

Don't patch your site using tracking tags!

!41

Page 42: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 3: Container script considerations

Summary

You’ve given thorough consideration to the system design taking measurement into account amongst other equally important design aspects. You will now proceed with the technical planning and execution of your TMS implementation.

Having spent time and effort designing the system to cater for the planned data capture, the quality of the implementation will still have significant influence over the success or failure of the measurement.

This chapter discusses a selection of topics that you need to carefully consider as part of your implementation. Ignoring these key points can hamper a project - make sure these subjects are on your agenda:

- Where to put the TMS on the page - does it matter? - Synchronous and asynchronous tagging - A/B testing and personalisation

!42

Give thought to the tactical implementation of measurement as well as the strategic planning:

plan well and build it right

Page 43: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

The decision on where to put the TMS script on the page is either not given sufficient consideration time and effort or causes paralysis through worry and agonised over-thought.

Having become desensitised to the importance of this decision through happy and casual placement of the asynchronous Google Analytics tracking snippet, developers take a cavalier attitude towards asynchronous script placement and behaviour.

A poor choice of script placement will degrade data quality in certain use cases. As we will see later, ignorance of your tags and their behaviour can be detrimental to the functionality of the site.

Real world restrictions may prevent the current script placement recommendations and guidelines from being followed to the letter. Furthermore, these recommendations have changed in the past and will change again. The script will change as the product matures and grows - to expect the script content and placement to be set in stone is naive and unrealistic.

Be smart about container script placement. You need to be aware of how the script behaves, what tags you have in your container and how they function. This enables you to make informed decisions as to how best to place the container and have realistic expectations of the potential consequences.

!43

Page 44: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Container script location considerations

Data capture accuracy For maximum data accuracy we want tags to fire as soon as possible. In a similar fashion to the contemporary asynchronous GA script, as soon as we can start taking measurements, we need to make sure the script can do so.

Alternatively, we may want a particular event to finish before conducting measurement. For example, we may need the entire DOM to complete loading so that we can measure a video player or we may need to measure user interactions with AJAX loaded content only when the AJAX call has completed.

Whilst we can start measurement as soon as possible, we can still control (to a degree) when measurements take place.

Hence, a sensible conclusion is that the sooner we can load the GTM container the better. Once it’s on the page, we can take more control over the order and timing of measurement execution.

Typically, the asynchronous nature of the GTM container script means that there is little or no risk of blocking other assets from loading and having a terminal effect on the loading and behaviour of the page. More on this later…

You need to carefully consider the use cases where synchronous loading can be used as well as the potential advantages and disadvantages of this choice.

!44

Page 45: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Asynchronous versus synchronous The use of asynchronous scripting eliminates a single point of failure on your pages. If an asset fails to load when using asynchronous loading, other assets will not be affected.

It also means that exact tag firing timing cannot be controlled.

The order of tag firing can be controlled in terms of when tags start, however, you need to also consider when tags complete. The point at which the tracking pixel request is sent may be some time after the execution began depending on the tag, trigger and variable functionality.

Be aware of the tag firing order and test at scale and under load to avoid unpredictable measurement behaviour.

Apart from unpredictable measurement behaviour, you may require exact timing and control of tag execution as part of testing or personalisation functionality as will be discussed later.

Loading the container from an external source The GTM container script will load the gtm.js typically using a line of HTML inserted onto the page such as:

<script async src=“//www.googletagmanager.com/gtm.js?id=GTM-ABCDEF”></script>

There are two key parts to point out here. First, the lack of http or https on the src attribute means the page protocol will be respected. Assets will be loaded onto the page using the same protocol as the page without introducing http assets on

!45

Page 46: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

an https page. Secondly, the use of the async attribute : This 7

attribute ensures the script will be run asynchronously as soon as it is available. Whilst it’s not available and is still downloading, the rest of the page can be rendered without delay.

Now, consider putting the GTM container script in an external library. We may choose to do this so that only one extra line is required in our page templates. This is much cleaner and easier to manage, no? What if we dropped the line below on our pages rather then the whole container script?

<script type="text/javascript" src=“http://www.mysite.com/scripts/gtm_container.js”></script>

There is plenty of risk here. The protocol used to load the gm_container.js file is hard coded as http - not a good start. The script tag does not sport the async attribute. So, whilst the GTM container script is loading the gym library asynchronously, the file in which the container script has been placed is loading synchronously which is potentially blocking the page.

By taking this route we have undone all the good work found in the default container script.

If you choose to implement the GTM container script in an external file, ensure the file is loaded respectfully in terms of the protocol and the async attribute.

http://www.w3schools.com/tags/att_script_async.asp7

!46

Page 47: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

A/B Testing and personalisation with GTM

Tag management is often sold with the promise that you won’t have to trouble the developers or the IT department again. This is a serious misconception. 8

The ability to deploy myriad tag types to your site without engineering hassle is a double edged sword. Harm can befall those who abuse this privilege and misuse the tool to cut corners.

Let’s explore a pair of use cases where synchronous execution is preferable and look at why careful choices need to made.

Deploying a simple A/B test on a page seems like a straightforward requirement to start with. We know that users need to visit the control page in order to participate in the test. If our tags fire asynchronously, what might happen to the measurement when they arrive?

A: The testing tag decides to keep the user on the original page. Then GA pageview fires. B: The testing tag decides to redirect the user to the B version of the page before the GA pageview tag fires. C: The GA pageview tag fires and then the testing tag decides not to redirect to the B variation.

http://www.slideshare.net/juliencoquet/superweek-2014-julien-coquet-tag-8

management-is-not-a-miracle-cure!47

Tag Management is not a miracle cure, it’s chicken soup for your tags

Page 48: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

D: The GA pageview tag fires, records a pageview and the user is then redirected to the B version where another pageview fires

In increasing levels of alarm and harm, scenarios A and B are barely acceptable. Yes, the resultant data is correct but this is most likely due to a lucky win in a race condition. The data is not reliable.

C starts to get risky - the resultant data is only correct because the user is not redirected to the B variation.

Scenario D is a disaster - everything that could go wrong due to asynchronous tag firing did and we end up with meaningless data.

We clearly need to control the order in which measurement and testing tags execute in order to have reliable data. IF we choose to fire test and measurement tags synchronously we are engaging in a contract. The small print on the contract needs to be read, acknowledged and understood:

1: Our measurement and testing tags will now block all other assets on the page.

2: If our measurement or testing tags fail, our page may not load.

3: Even if our measurement and testing tags fire at the correct time, if they are not built with maximum efficiency in mind, we may affect user experience.

!48

Page 49: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

4: Choosing synchronous tags is a risk that we are taking in order to serve our own data needs.

Point 4 is quite interesting in that we are recognising that we are risking user experience and the success of the site to serve our own selfish data needs!

Yes, we are measuring and testing in order to learn about user behaviour and to optimise the site for the users but we are still the first beneficiaries - doesn’t this seem terribly selfish?

Personalisation lets us try to justify choosing synchronous tags.

Personalisation will typically involve a dynamic content choice in order to serve the best content to the user. This requires clever modification of the page content whilst the page is loading.

The reasons for the unpredictability of our A/B measurements will also cause unpredictable behaviour when our ad hoc content is dynamically inserted into the page, so, we need synchronicity to help us here.

The same warnings apply - be certain that your scripts are rock-solid reliable and fast. Acknowledge the risks you’re taking with synchronous tagging and take every measure possible to mitigate them.

Asynchronous tagging should still be your default path but recognise when an how to choose the alternative.

!49

Page 50: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 4: Reliable dataLayer implementation

Summary

Tag management solutions make use of JavaScript data structures to act as a messaging conduit between presentation and measurement systems.

The JavaScript data structure used by GTM, the dataLayer, is essentially an array. JavaScript array and dataLayer basics are simple to grasp. The basic functionality of the dataLayer will quickly become second nature but this is where problems can start to happen.

There are traps that are easy to fall into that will render your dataLayer unreliable. These traps will harm the quality of your data and are best avoided:

- Anti-pattern - failing to implement the dataLayer respectfully - Anti-pattern - failing to sanitise data in the dataLayer - Render the dataLayer in a reliable manner - escape user input - track failures

!50

Page 51: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

The GTM container script is a clever little snippet of JavaScript that we can learn a lot from.

The GTM container script has to perform quickly and safely with no risk to other scripts, the dataLayer or the data already pushed onto the dataLayer.

How this is done is an important lesson and can serve as a useful technique to solve for a number of anti-patterns as we will see.

Given that the dataLayer is such a fundamental part of the system, failing to use it safely and properly will cause major problems in your GTM implementation.

!51

Treat yourself to some brain treasure: understand how the GTM container script works

Page 52: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-Pattern - failing to implement the dataLayer respectfully

A key function of the Container script is to set up a dataLayer. The initial declaration of the dataLayer is a good illustration of a safe and respectful way to share global variables on a page between scripts.

The Google Tag Manager documentation introduces the topic of dataLayer instantiation using the simplest method possible:

To set up your data layer, add the following snippet of code to the head of your page (or elsewhere above your container snippet):

<script> dataLayer = [{‘foo’:’bar’}];</script>

Simple, right? Arguably the documentation has to start with the simplest technique as an introduction but using this method universally will lead to issues. This is really quite dangerous if you fail to understand how it functions.

What if someone else has already pushed a message onto the dataLayer, a transaction for example? If you declare the dataLayer using an assignment as above, the old data will be over written. Not good.

Referring back to the container script, the correct technique is to check to see if the dataLayer variable already exists before doing anything. If it does exist, push messages onto it (it’s an

!52

Page 53: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

array remember?) and if it doesn’t, then you can create a new empty array and push messages onto that:

<script> window.dataLayer = window.dataLayer || []; window.dataLayer.push({‘foo’:’bar’});</script>

Don’t assume that there are no other scripts that may have set the dataLayer already. It’s better to respectfully declare and push as shown in the example above.

!53

Be respectful and considerate when declaring or pushing to the dataLayer

Page 54: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-Pattern - failing to sanitise data

An empty dataLayer is quite a dull thing. In reality you’ll push all manner of interesting and useful objects onto it. For example, let’s push a message onto the dataLayer regarding a product:

<script> dataLayer = [{ 'productID': ‘1234', 'productName': ‘Widget’, 'productColour': ‘blue’, 'productSize': 'XXL' }];</script>

Apart from an unsafe dataLayer declaration, this script looks quite benign at face value. A key piece of information regarding the use of this script is not immediately obvious. It has the potential to cause serious issues.

The value of each variable will be rendered by a server-side script. A Ruby partial, a PHP template or whatever your server side language of choice uses. Even though the variable values are rendered by a script, the original source of the data was a human:

These values contain user input.

The first rule regarding user input is that you will always sanitise user input.

!54

Page 55: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The second rule regarding user input is that you will always sanitise user input.

No matter which system was the source of the data - sanitise data from a 3rd party.

One day the product name changes. You’re not told as it’s a stock management function. It’s only a value change - what’s the worst that could happen?

This:

<script> dataLayer = [{ 'productID': ‘1234', 'productName': ‘The world’s best Widget’, 'productColour': ‘blue’, 'productSize': 'XXL' }];</script>

Because the productName value has not been sanitised, it contains a single quote character which causes a Javascript syntax error every time this script is executed. This may result in no transactions being recorded. Other scripts may fail. All revenue reporting will now cease. This is not a good day.

!55

Always treat user input as tainted data. Use caution.

Page 56: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design Pattern - tracking dataLayer failures

If you expected this book to include a GTM technique to ensure the dataLayer always functions and always contains safe and valid data then you will be disappointed. The job of GTM is to manage tags - not sanitise user input. User input cleansing is a function of other system components - front end validation, sanitisation and correct storage on the business and database layers.

What can we do about this situation? Whenever a dataLayer is rendered on a page, assume the dataLayer rendering will fail and allow for it.

Learning from the dataLayer instantiation pattern demonstrated by the container script, the first change to make is to safely and respectfully instantiate the dataLayer in a separate script block:

<script> window.dataLayer = window.dataLayer || []; </script>

Move script responsible for pushing data onto the dataLayer into another script block. The dataLayer push will be performed by an appropriately named function called ‘messagePush’.

!56

Page 57: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

<script> window.dataLayer = window.dataLayer || []; if(typeof(messagePush)===‘function’){ messagePush(); }else{ window.dataLayer.push({ 'event': ‘gtm.pageError’, ‘errorMessage': ‘dataLayer error’, 'errorPage': document.location.pathName }); } </script>

If messagePush is not available to use, we can assume the worst and report a likely dataLayer failure to GTM so that error tracking scripts can help us monitor this failure mode.

The type of the messagePush method can only be ‘function’ if it is syntactically correct. Any failure will result in an error event being pushed onto our dataLayer to be handled appropriately when GTM has started:

<script> var messagePush = function(){ window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'productID': ‘1234', 'productName': ‘The world’s best Widget’, 'productColour': ‘blue’, 'productSize': 'XXL' }); };</script>

!57

Page 58: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This approach is most appropriate for use on mission critical tracking. The extra weight added may not merit universal deployment but consider using this type of technique in a template on a transaction receipt page where tracking must be rock solid.

Design Pattern - tracking JavaScript Exceptions

Ensure you have tags that are triggered by the gtm.pageError event fired by the built in JavaScript error exception listener.

JavaScript errors are generally poor for user experience. They are wasteful and can have unpredictable effects on tag, trigger and variable behaviour.

Using native error tracking to fire non-interaction GA events should be a default technique in your armoury.

Make sure the error, page and line number are tracked to aid tracing and resolution.

!58

Page 59: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Section 3 - Conversions

Ensure the best quality data is delivered to measure your Key Performance Indicators. You've championed data quality over data volume. You've got system designs that will deliver the key metrics for your business.

Now measure your key outcomes using these design patterns to ensure you get the data quality that the business requires.

!59

Page 60: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 5: Page level data measurement

Summary

Analysts look at data in reports and pose the seemingly basic and straightforward questions below:

- Are these the pages that were viewed by users on my site? - Is this pageview volume, bounce rate and time on page data that I can trust?

Page level data is easily delivered by vanilla ‘out of the box’ installations - we’re talking about pageviews which shouldn’t be regarded as Rocket Surgery or should it?

It’s very easy to deliver data that fails to answer these question and more sophisticated questions derived from them. Unfortunately, and all too often, the resultant data used in reports is rarely robust enough for most analysis requirements and less useful for extracting insights.

First, you need to be able to recognise poor data. Knowing, understanding and being able to recognise the anti-patterns that deliver poor quality data will help you to avoid them.

!60

Pageviews are easy to measure but hard to measure well.

Page 61: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Allow me to introduce a complex-but-should-be-simple subject by dealing with some straightforward and quite common questions about page level data:

What does good page level data look like? What does bad page data look like and why is it bad?

Good quality page level data is apparent when it exhibits two clear characteristics:

- You can see the on-site user behaviour clearly represented by the data. - The page data is an accurate representation of the site content.

Good page level data is rich with semantic value. You can see the flow of visitors coming from the traffic source, viewing pages and completing conversions or exiting the site.

Poor quality page level data will obfuscate these properties making analysis and therefore insight extraction much longer and harder.

What problems are caused by bad page data?

Insights are harder or impossible to see with bad page data. You will need to continuously check what a page is for, what it

!61

Poor quality page level data will seriously hamper analysis and insight extraction

Page 62: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

contains and where to find it on the site. This is not a productive experience for an analyst.

While trying to form hypotheses regarding user intent and behaviour, if an analyst constantly has to check which page they are analysing, the time and effort costs will increase vastly.

If the page URLs mean nothing or are confusing to the analyst, the likelihood is that users and search engine bots will experience the same confusion.

How does bad page data happen? What is done wrongly and why? Where does tracking fall down to cause this and how do we stop it?

The qualities of a well planned and well designed site with a clear, concise and logical URL structure will be apparent to the user, search engine bots and analysts for very similar reasons.

A well planned, designed and implemented site is not an accident. It is the result of the design process that was described earlier. Poor quality data is symptomatic of a failure to include measurement in the design process. Poor page level data is only one instance of a spectrum of data issues that result from dealing with measurement late or not at all in the this process.

!62

Recognise the scenarios where poor quality page level data will be generated

Page 63: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

You can spot sites that probably have poor quality page data as they will include features such as:

- Sites with inconsistent URL structure - Single page sites - Sites with non-descriptive URLs - URLs with no semantic value - Sites with mixed case URLs - Spelling errors in URLs - URL changes - 302 and 301 redirects - iFramed content - Badly implemented AJAX - Forms that post to themselves - 100% virtual pageview sites - Sites with massive page titles and URLs

When these anti-patterns are eliminated GTM will help you easily deliver high quality page level data. Avoid these anti-patterns and the temptation to fix up a poorly designed and executed site. Capitalise on the wealth of GTM and GA features and deliver rich page data.

!63

Page 64: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-pattern - URL problems

The first major data quality issue to discuss is the single page site. This is the type of URL you might expect to see:

http://mysite.com/index.aspx?pageid=abc123

Which page on mysite.com does this URL refer to? Who knows? You can't tell from this URL.

Do such sites still exist? Sadly, yes. The technique is still widely used and is a source of pain for developers and analysts.

Seeing a content report in Google Analytics - all pages, landing pages, exit pages or Goal URLs - with this kind of data is what we’re trying to avoid.

URLs like this be a consequence of choosing a blog engine to run a site. However, most contemporary blog engines will allow a URL to be generated based on the page title so this type of data really is inexcusable. Form heavy sites also exhibit this anti-pattern. Where multiple surveys are often published and change often, the function of the survey takes precedence over the structure and content of the URL. This type of data suggests lazy development and poor design or a lack of thought regarding measurement during design.

Using IDs in the URL results in a lack of semantic value - the URL has no meaning. As has been alluded to already, the meaning of the URL is important to the user, search engine

!64

Build logical, clean, and semantically rich URLs

Page 65: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

robots and analysts. Even where IDs aren’t used, there is still scope for poor data to be generated:

Avoid abbreviations, idiom and jargon. Use the vocabulary of your users in URLs and page titles.

Make sure your spelling is correct and case usage is consistent. This seems obvious but a consequence of your URLs being misspelled or containing odd capitalisation is that the rest of the internet may choose to use the correct spelling and will fail to find the page. Furthermore, incorrect spelling of page titles and URLs will affect the correct functionality of triggers and variables. You may have the correct spelling in your GTM assets but if the site fails to mirror your accurate implementation, unpredictable tracking behaviour will result.

Anecdotally, analysis projects have been documented as delivering unexpected results where spelling errors have not been flagged up. This has lead to the right analysis on the wrong data.

!65

Page 66: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Redirects and iFrames

Redirects and iFrames are evil . Let me explain. Redirects 9

and iFrames are so popular yet their use is widely misunderstood. The effects on user experience, organic performance and measurement can be serious but are rarely appreciated.

Redirects

Consider the scenario where you see a link in the Google search results. You click the link offering green widgets and you end up on a page that offers you red widgets - this clearly does not match what you expected. Not good? Imagine how the Google search bot feels.

Your feelings will be hurt even more if you experience the same scenario when clicking a link on a site (mid journey) and the page that is returned fails to match what the link promised.

Authors opinion9

!66

Page 67: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Such behaviour is jarring for the user and difficult to measure accurately for the analyst. Furthermore, Google takes a dim view of deliberately malicious or badly implemented redirects potentially leading to impact on organic 10

performance.

Common bad practice is to incorrectly configure temporary redirects (HTTP response code 302) that don’t preserve referral information or querystring parameters. The resultant loss of data can be catastrophic especially if cross domain tracking is being used.

Other measurements can be configured to rely on referral or querystring data - the lack of either will affect GTM functionality and harm the accuracy of measurement.

A frequently observed anti-pattern is when the redirect is fired on a page using javascript. The redirect will fire before a

http://googlewebmastercentral.blogspot.co.uk/2014/04/webmaster-10

guidelines-for-sneaky.html!67

Page 68: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

tracking pixel can be sent to Google Analytics resulting in an unmeasured pageview. This is highly undesirable and can lead to self referrals, and lower than actual pageview, exit, time on page and bounce rate metrics.

You can see redirects firing by using the network tab on the Chrome debugger or by using a Chrome extension such as:

https://chrome.google.com/webstore/detail/redirect-path/aomidfkchockcldhbkggjokdkkebmdll

In general, redirects are best avoided. In particular, mid journey redirects are unnecessary and are typically the result of patching site behaviour with no consideration for user experience, organic performance or measurement.

Sites that employ redirects will exhibit page level data that does not match reality. This will adversely affect one of the key requirements for pageview data - the user journey in the data needs to be clear and accurate. The metrics will be skewed and incorrect conclusions can be drawn from the data. Hypotheses will be formed that are at best, time wasters and at worst, misleading and dangerous.

iFrames

iFrames are an illustration of lazy development . Careless 11

reuse of content in an iFrame smells of a hurried implementation where correct content reuse has been ignored

Authors opinion again11

!68

Avoid redirects where possible

Page 69: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

in favour of ‘getting the job done’. The job has not been done. Measurement, organic optimisation and user experience have been ignored in order to get an item off a to-do list.

Rendering an iFrame on a page essentially creates a new instance of a browser. Assuming the page in the iFrame belongs to the same domain as the outer page, the container tag will be loaded recording a pageview for the iFrame. Two consecutive pageviews will show the time on page for the outer page as unrealistically low.

Worse still, the dataLayer rendered in the outer page will not be ‘visible’ to the container in the iFrame and vice versa.

A worse scenario to cater for is the iFrame containing 3rd party content. Historically this was an issue requiring cross domain tracking to be used. The iFrame source needed adjusting to enable cross domain tracking. The 3rd party content required a cross domain Google Analytics script. All quite messy.

The motivation for using an iFrame in this case is often a result of the inability of the 3rd party content to be correctly integrated into the site.

The need to patch the measurement of the included content with Google Analytics scripts brought the solution back to square one and the Google Analytics script gets left off as it’s too hard.

!69

Avoid iFrames where possible

Page 70: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This is criminal negligence when the 3rd party content contains a form that represents a key conversion on the site that needs to be measured.

Contemporary solutions offer fewer hurdles to implementation using Universal Analytics automatic cross domain linking. The main requirement is to have the 3rd Party content render the GTM Container script – sadly, also often not a trivial challenge.

In summary, the motivation for avoiding iFrames and redirects is a carbon copy of the reason to design and build correct markup for links and click tracking:

- Improved Organic Performance - Easier maintenance - reduced complexity - Improved measurement - Enhanced user experience

Redirects and iFrames introduce complexity that is detrimental on many levels. The apparent fix is far from a solution and introduces a raft of deeper issues. Fixing these issues will be more expensive than addressing the original problem will have been.

AJAX forms

Asynchronous JavaScript And XML is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server

!70

Page 71: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

asynchronously (in the background) without interfering with the display and behavior of the existing page. 12

This definition poses a number of questions regarding the measurement of user interactions involving AJAX. Use of AJAX in itself should not be an issue. The risk is that the behaviour of an AJAX form or site is not well understood leading to flawed page level data. Use of AJAX techniques is not an anti-pattern in itself but this scenario needs careful thought and planning with regards to measurement. You can make it work if you think it through.

The key point is that web applications can send and receive data without interfering with the display and behaviour of the existing page. There is no page transition to fire a pageview and the page URL does not change

Happily, the normal operation for AJAX requests means there are discrete events (success, error or complete callbacks) that can be used as measurement hooks. These hooks can be used to push custom events onto the dataLayer, firing a virtual pageview to record the AJAX form submission.

Obviously the resultant pageview data will be artificial in that there are no pages that exist that match the recorded virtual pageviews. This is a double edged sword.

http://en.wikipedia.org/wiki/Ajax_(programming)12

!71

Using AJAX demands well designed and implemented measurement

Page 72: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

On one hand the reporting limitations are trivial: in-page analytics and links to pages from reports will not work. On the other hand this scenario gives you the opportunity to send the most semantically valuable data to Google Analytics. This means that useful and solid data can still be generated if care is taken over the design of the measurement.

A better alternative for AJAX measurement

If coupling the AJAX functionality to the measurement layer sounds clunky, that’s because it is. Happily, the HTML5 history API and GTM History events give us another potential 13

solution that is more elegant and preferable.

Unfortunately not all browsers support the history API. The browsers listed below provide some support for the history API:

- Firefox 4+ - Google Chrome - Internet Explorer 10+ - Safari 5+ - iOS 4

If a site uses AJAX functionality, using the history API means that page transitions can be recorded without relying on AJAX callbacks to push events on to the dataLayer.

GTM History events enable the accurate measurement of site functionality and content changes using Google Analytics.

https://github.com/browserstate/history.js/wiki/The-State-of-the-HTML5-13

History-API!72

Page 73: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

In summary, decoupling the AJAX functionality from the measurement layer is best achieved using History events. This requires the history API calls to be sufficiently decorated with meta data about the state change to be useful. This is no different to well designed and well built markup. The reality is that a decision was made to use AJAX and so the design and implementation need to support the all requirements – technical, functional and measurement.

Forms that POST to themselves

A frequently used anti-pattern that bears a striking resemblance to the AJAX measurement challenge is a form that POSTs to itself. In this scenario the POST is a normal browser submit - not an AJAX execution, and even though the content is updated the response from the server does not change the page URI.

Each successful user interaction results in two pageviews and 1 unique pageview being recorded. Unsuccessful user interactions (users not submitting the form) will be recorded as one pageview and one unique pageview.

Without thought for the measurement of the form, teasing form submission data from form view data is not possible - both interactions report the same pageview data.

Happily there are solutions to this challenge. The first is very similar to the AJAX measurement pattern. Rather than using the AJAX hooks or the history API, the form post response

!73

Recognise where key measurements need to be made

Page 74: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

content needs to contain a dataLayer custom event to fire a virtual pageview.

The resultant pageview data is now suitable for use in a goal configuration.

The second solution is covered in detail in the Form data capture best practices chapter.

100% virtual pageview sites

Judicious use of virtual pageviews is a valid and useful technique but it is open to abuse. Using virtual pageviews across an entire site is heavy handed and can result in brittle data being generated that bears little or no resemblance to the site.

The need to use 100% virtual pageview based data may be as a result of poor URL structures. This is a demonstration of fixing a site using the measurement layer. The fix is only valid for the data and does not address more fundamental issues such as user experience and organic performance.

Solutions that exclusively use virtual pageviews assume the analyst has intimate knowledge of the site. Often, this will not be the case and will hamper analysis.

Use virtual pageviews as required. If use is rife, consider how the system design has lead to the situation – you need to consider a better design.

!74

Page 75: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

URL and page title essays

Google Analytics is very accommodating regarding the amount of data that can be sent for processing from a site.

The Universal Analytics request payload size limit length is well known . These limits are very generous but should this 14

threshold be fully indulged at every opportunity?

To stuff the collect request with an essay comprised of the URL, page title and all the other data points will have performance issues (the data is POSTed rather than sent via a GET when it passes 2048 bytes) as well as making reporting harder.

Long page URIs are presented in the content reports using line breaks to fit the data in the report table and the data becomes harder to read. The same issue stands for the page titles too. Comparing long but similar page titles and URIs is hampered by overly long strings of characters. Whilst avoiding abbreviations where possible, a concise URI is preferable to the analyst.

When long page URIs are unavoidable, using content grouping allows a rationalised view of aggregated data. Where the page URIs may not be shortened to an acceptable limit, the choice of the content group name can make up ground.

https://developers.google.com/analytics/devguides/collection/protocol/v1/14

reference#maxlength

http://analytics.blogspot.co.uk/2011/04/leading-industry-with-tracking-code.html

!75

Page 76: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Page titles and URIs do not need to be packed with every conceivable piece of data all at once. Remember, data pertaining to the visit, traffic source, device usage, user type, browser and technology are all captured separately and do not need to be part of the page URI.

Keep the page URI and title descriptive but not overly verbose to ensure the data quality is good enough and not unwieldy.

One pageview tag to rule them all

Having successfully eradicated all the anti-patterns from your page measurement you are now in a position to capture rich page level data using Google Tag Manager. You are probably thinking about using the full suite of Google Analytics tag decoration techniques including (but not limited to):

- Content grouping - Custom dimensions - Custom metrics - Virtual pageviews - Enhanced Ecommerce

Using a combination or a selection of these decorations can cause confusion. You may be tempted to use a trigger to fire a page view tag that contains content grouping data, a separate trigger to fire a tag to decorate with custom dimension data and another trigger/tag combination to fire of an enhanced ecommerce transaction.

Don’t. Instead, use the behaviour of undefined variables to build a lean set of tags.

!76

Page 77: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

If you embark on the route of specific tags with specific functions, the number of tags in your container will grow and they will be hard to manage and understand.

Be aware that using variables to populate fields in tags does not require any logic to fire the tag only when the data is present.

If the data is not available, the variable will return a value of undefined. In the case where variables return undefined, no data is set. This means you can decorate your page view tag with custom dimensions, set the enhanced ecommerce flag, populate the page title and page path fields with variables and these data points will only be set when the variable returns a value that is not undefined.

Of course, this means that you need to be certain what data types your variables return and that when the data is not present, undefined is returned but this should be standard practice.

Using this technique will deliver a lean set of tags that do just what you want.

!77

Page 78: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 6: Tracking clicks

Summary

Beyond pageviews, click tracking is one of the most fundamental building blocks of online data capture. In a very simplistic view of web usage, users view pages and click links.

Clicking a link is a simple action but all too often the nature of the implementation of the link leads to a series of issues that are detrimental to accurate data capture.

Project costs escalate and data-chaos reigns when common link click tracking anti-patterns are employed. This is a detailed exploration of the direct impact of a number of anti-patterns:

- Anti-pattern - Rampant DOM traversal - Anti-pattern - Inline event handlers - Design and build with the data exhaust in mind. 15

- Tracking clicks and recording outcomes using DOM elements appropriately decorated with meta data - Using Auto event tracking in GTM

http://dictionary.reference.com/browse/data+exhaust15

!78

Click tracking is so important but often subject to serious implementation issues

Page 79: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

A special case of click tracking involves sub-domain and cross-domain linking. We’ll see a demonstration of a simple anti-pattern to arm you with a heuristic to help you choose when, how and why to do cross and sub domain click tracking and how to make it easier:

- Anti-pattern - domain naming choices - Using Universal Analytics automatic domain linking in Google Tag Manager

!79

Page 80: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Imagine you own and run a major news site on the internet. One of the most important clicks you need to measure is the link to the main news section in the main menu.

You’re forming a hypothesis regarding how the text and style of the link affect user behaviour. Obviously you need some baseline data to measure the experiment against. You choose to compare the click volume with the footer link but you find that all the links were marked up like this:

<a href="#" onclick=”goNews();” class=”topLink”>News</a>

That’s it. Nothing else. This is not a helpful snippet of markup and here’s why:

You scan the HTML on the page and find 27 instances of links with the class of topLink - all in the menu. To make matters worse there are three instances of these links with goNews as the inline click handler. This means there is no way of uniquely identifying the link to track clicks on it.

By now, the hampering effects of the markup should feel obviously counter intuitive to you, me and the developer. This is the kind of implementation where you look back and wonder what the thought process was when it was built. This highlights the danger of not thinking about what you want to measure as you construct the HTML.

!80

Markup quality has a direct impact on the success of your measurement and data quality

Page 81: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Look further and you can see that seven levels up the DOM tree, there are containers that do have unique ID values but when you load other pages you find these IDs are random and change on each page.

Anti-pattern usage is rife here. Let’s discuss these patterns and develop some techniques to avoid them.

!81

Page 82: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-Pattern - Rampant DOM traversal

Rampant DOM traversal is a commonly chosen quick fix and leads to byzantine complexity and brittle measurement solutions. First we need to be clear what the problem is: say you need to identify a DOM element to track how users interact with it.

<a href="#" onclick=”goNews();” class=”topLink”>News</a>

As we saw earlier, the problem is that there is no way of uniquely identifying the element when it is clicked. So you start to look upwards and outwards...

<div id="HeaderLink"> <span> <ul> <li>…</li> <li>…</li> <li>…</li> <li> <a href="#" onclick=”goNews();” class=”topLink”>News</a> </li> </ul> </span> </div>

!82

Avoid long distance DOM traversal when identifying elements

Page 83: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Okay, so you can see the great great grandparent tag does have a unique ID. Perhaps we can use this instead? Before you decide to do this ask yourself ‘Can I reliably identify this link using the great great grandparent tag ID? Are my site page templates rock solid and stable or do they change often?’ If the great great grandparent element attributes are likely to change then this will break the click tracking solution.

Isn’t there is a risk that the attributes of the element itself will change? Yes, however, think about the great great grand parent of the tag. When so many more DOM elements are involved in the equation, the likelihood of them changing increases significantly. When attaching an event handler to an element based on a lengthy hike across the DOM the likelihood of failure increases significantly with each DOM level traversed. With this in mind, use CSS paths with care.

Avoiding this anti-pattern requires the decoration of elements with enough semantic value in the attributes to enable reliable identification of the element without rampant DOM traversal. Element attributes are easily extracted and used in GTM variables - feel free to exploit this excellent feature.

Make a sensible judgement call regarding how far you’re prepared to wander in the search for a solid foothold to identify your clicked element from. Maybe you could handle a 4 level traversal? If you’re willing to bet your tracking solution on this decision you could miss out on the extra treasure that you’ll inherit from just writing good markup such as improved organic search performance and the maintainability of the markup.

!83

Page 84: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The reasons to decorate links with meta-data outweigh the arguments against:

For: - Improved readability - Improved maintainability - Improved tracking - Potential organic performance improvements

Against: - Page weight - Development time

!84

Page 85: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-Pattern - inline event handlers

If you plan to track clicks using GTM auto event tracking then there is a very reliable way to ruin your day - inline scripting on links.

Start with the bad practice of not using unobtrusive javascript:

The functionality of the page becomes tightly coupled to the content.

The readability and therefore the maintainability of the markup suffers.

Inline script is not cached like external scripts so there is an unavoidable performance penalty.

Now, ask the question ‘what is the script doing on the link?’. It’s a link and this is what links are for:

Links are found in nearly all Web pages. Links allow users to click their way from page to page. 16

So, something else is also happening when the link is clicked. What is happening, why and what could this mean to the measurement solution?

http://www.w3schools.com/html/html_links.asp16

!85

Inline scripts are evil and should be avoided

Page 86: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

In days of old before the ‘Wait For Tags’ functionality was available in GTM linkClick and formSubmit listeners, the setTimeout technique was employed as a ‘better than nothing’ route to tracking link clicks:

jQuery(el).click(function(e) { e.preventDefault(); _gaq.push(['_trackEvent', category, action, label, value, interactive]);

setTimeout(function(){ document.location=el.attr('href'); }, 250); });

This was not a 100% solid solution. The timeout duration was undesirable and could still miss clicks. This technique either obliterated any inline click handler or was equally stomped on depending on the inline click functionality. Now we have the luxury of ‘Wait For Tags’ in listeners.

Take a careful look at the text describing the ‘Wait For Tags’ option:

Delay opening of links until all tags have fired or the specified timeout has elapsed, whichever comes first.

The browser is prevented from letting the link take the user to the next page until tags have completed. This is much more reliable than a set-in-stone 250ms delay with the setTimeout. The worst case scenario uses the maximum delay rather than an immutable and wasteful 250ms.

Use this option to ensure the metric from the click is correctly recorded. Unfortunately, if the link employs inline script to

!86

Page 87: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

handle clicks then it is still possible to bypass the standard functionality of the browser resulting in unexpected behaviour.

Take this piece of HTML for example:

<a href="/index.html" onclick="document.location='/index.html'">a link<a/>

There is no point to the onclick event handler. It does exactly what the link would normally do with the added bonus of disrupting the predicted functionality of any GTM link click listeners. The inline onclick does not respect the standard browser functionality.

As well as affecting the expected functionality of links, onsubmit inline scripts on forms have similar issues. This example is extreme for illustrative purposes. There may be legitimate reasons for using inline scripts. Ideally, unobtrusive scripts would be used rather than inline scripts.

In the same way that the measurement layer is not permitted to dictate functional limits, with proper design, functionality does not hamper measurement. Correct employment of best-practice engineering means that inline scripting is relatively easily avoided. Thinking cohesively about design, measurement, functionality and implementation, as described earlier, is important to be able to produce a solution that ticks all the boxes.

The potential valid uses for JavaScript event handlers are legion. Considering the general reasons for handling click events on links we can see two very general categories here:

- Measurement - Functionality

!87

Page 88: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

If the click handler is used for some sort of measurement outside of Google Analytics or your primary digital analytics system, consider using the dataLayer as a conduit for messaging between the presentation and measurement layers. Avoid coupling the presentation layer to your measurement system with native method calls.

If the click handler is used to deliver functionality that is not standard for a link, is a link really the right tag to use? Are you trying to mimic a button on a form? If so, use a form and a button.

Design Pattern - using meta data and auto event tracking

Take another look at the news site link discussed in an earlier example:

<a href="#" onclick="goNews();" class="topLink">News</a>

In reality the link looks like this:

<li class="orb-nav-news orb-d"> <a href="http://www.aNewsSite.co.uk/news/">News</a> </li>

The clickable element doesn’t have a unique ID but the parent has a class. There are multiple instances of elements with the orb-nav-news class on the page though, so the DOM traversal to inspect great great great grandparents is too risky to be a valid technique.

!88

Simple but powerful markup & GTM in action

Page 89: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Instead, assume the element is decorated with an ID as well as having the class on the parent:

<li class="orb-nav-news orb-d"> <a href="http://www.aNewsSite.co.uk/news/" id="header-nav-news">News</a> </li>

Now we’ve got a solid candidate to fire an event using a built in trigger to extract the clicked element ID.

When an element with an ID equaling header-nav-news and a parent with a class that contains orb-nav-news is clicked we can fire our event. The single step of DOM traversal is easily accomplished using a dataLayer variable:

gtm.element.parentElement.className

In this example we’ve added just enough metadata to allow 17

the easy identification of an individual element. The meta-data is semantically valuable, easy to read and quite manageable.

The important takeaway from this example is the absence of script and the presence of clear and readable markup leading to a solid and reliable link click tracking solution.

https://twitter.com/jeffalytics/status/45934042324561920017

!89

Metadata is a love note to the future

Page 90: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Cross domain link tracking

This is a special case of handling link clicks. Clicking a link to another domain or subdomain that is considered part of the same web property does not require measurement as such. The link is decorated with data that will be used to identify and maintain the Google Analytics session.

Pre-GTM, the classic GA script solution was a mine field. Even simple sub-domain tracking required a change to the tracking code. The correct values to use in the cross domain script were confusing which often resulted in inconsistent and faulty implementations. Cross domain tracking required all cross domain links and forms to be decorated with a javascript method call so that when the link was clicked or the form submitted the GA session data was passed on to the 3rd party domain.

The examples in the Google documentation used inline click and submit handlers . This method was obviously prone to 18

failure due to other inline script issues as discussed.

<a href=“http://mysite.tumblr.com”onclick=“_gaq.push(['_link', 'mysite.tumblr.com']); return false;">View My Site on Tumblr</a>

The result of broken cross domain tracking was often unusable data in Google Analytics and so, with this substantial risk, this often meant that this important tracking functionality was avoided.

https://developers.google.com/analytics/devguides/collection/gajs/18

gaTrackingSite!90

Page 91: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Common issues with subdomain tracking and cross domain tracking start with the domain naming convention and confusion as to what tracking code changes were required:

The cookie domain value for cross domain or subdomain tracking could be .mysite.com or mysite.com - the leading dot can be omitted but the most important aspect is that the value needs to be consistent.

If the choice was made to not use inline click or submit handlers, the challenge remained to unobtrusively detect links to all subdomains and 3rd party domains. Links and forms pointing at 3rd party domains required click and submit event handlers to call _link or _linkByPost correctly.

Not a trivial challenge.

URL Domain

www.mysite.com Original domain

blog.mysite.com Subdomain

shop.mysite.com Subdomain

mysite.tumblr.com Cross domain

facebooke.com/mysite Cross domain

twitter.com/mysite Cross domain

www.mysite.com/members Original domain

!91

Page 92: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design Pattern

The contemporary technique afforded by GTM for subdomain and cross domain tracking is to specify a comma separated list of domains in the Auto Link Domains setting in a Universal Analytics tag.

The highest likelihood of success requiring least effort with cross domain and subdomain tracking is delivered using the settings above with a Universal GTM tag. Bear in mind that this solution is still prone to unexpected behaviour when inline click and submit handlers are used.

As the saying goes, no code is better than no code or, less 19

cryptically, a solution requiring no software to be written is preferable to a solution where software changes are required.

http://blog.codinghorror.com/the-best-code-is-no-code-at-all/19

!92

Universal Analytics + GTM + Auto Link Domains = cross domain tracking success

Page 93: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design Pattern

In summary, the six components of successful link click tracking are:

1. Build the right markup to facilitate measurement

Use the guidance in the first chapter to build measurement into your design process and fully address it as early as possible. This means planning to decorate tags with meta data and avoiding inline scripts to handle events. Avoid employing scripts to manage functionality on links. If you’re contemplating using scripts to modify link behaviour, rethink the design and use an alternative tag.

2. Capture the data exhaust and make it available for all data consumers

Be aware that other systems also need to use the data generated by click events. Use the dataLayer as a message conduit for maximum efficiency. Be better by doing more with less.

3. Build simple

In the spirit of doing more with less, you will find that well designed and well built markup will result in simpler markup with a host of benefits. This is the very essence of building a site right - don’t aim to fix up poor markup later - you can’t do this effectively. This also means avoiding scripts to change

!93

Six guidelines for you to follow to make sure your link click tracking is solid

Page 94: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

link behaviour again. The simplest tag does what it is intended to. If you try to make it do something else with script, by definition this will not be the simplest solution and will most likely deliver sub-optimal results.

4. Use auto event tracking

Auto event tracking offers a solid solution that is massively preferable to inline or even unobtrusive click event handlers. If you’ve avoided scripts that mangle functionality in cruel and unusual ways then using auto event tracking will be a perfect fit.

5. Use natively supported cross domain tracking solutions with GTM

If your links point to subdomains or 3rd party domains that remain within your measurement universe, go directly to the native Universal Analytics cross domain tracking solution in Google Tag Manager. Avoid scripted solutions and especially the classic script route.

6. Don’t do dumb things

The examples used in the anti-pattern discussions fall easily within the boundaries of ‘dumb things’. It’s easy to mock prior decisions with hindsight so use this to your advantage and refactor mercilessly. Write drunk and edit sober - attack a problem and then weed out the questionable decisions as quickly as possible. Solid prior planning will minimise the need to engage in major refactoring.

!94

Page 95: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 7: Advanced user interaction tracking

Summary

Google Tag Manager is many things but it is not is the panacea for all tracking ills, woes and challenges. It has limitations, new features are being added but not all use cases are catered for out-of-the-box. This will be the case frequently but there is hope! Google Tag Manager can be extended to cater for all types of event handling and tracking. This section will describe the anti-patterns that are often used in extending GTM and the best practices that help avoid these anti-patterns.

Similarly, traditional techniques employ jQuery to inspect and traverse the DOM. Finding an element on the page before, during or after an event using jQuery offers some pretty powerful and tempting selector functionality.

Building on the click tracking discussed so far, this chapter describes:

- Inspecting and traversing the DOM in the dataLayer - Extending auto event tracking - when, how and why

!95

Page 96: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Auto Event Tracking is a powerful feature in GTM that massively reduces JavaScript development effort. The dependency on 3rd party frameworks and libraries such as jQuery is eliminated and cross-browser issues are handily dealt with.

Auto Event tracking is an excellent tool to use but only up to a point. The current scope of event listener coverage is healthy but it is far from exhaustive.

Indeed, beyond standard DOM events such as click or submit, what else can be listened for and tracked?

Extending the listening capabilities of GTM is simple but not trivial. The temptation to drop a jQuery event handler into a custom HTML tag is ever present but can be avoided. The solution is already built into Google Tag Manager as we’ll see.

When DOM events happen, you want to understand which element was clicked or submitted. Ideally the clicked or submitted element will have an ID or class that you can use. If not, you may need to query the parent element ID or class. As we have seen, DOM traversal is often required but caution must be exercised. How far can you go with DOM inspection

!96

Use GTM Auto Event Tracking rather than custom JavaScript event handlers

The DOM is accessible through the dataLayer.

Page 97: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

through GTM? Surprisingly far and you can do it the right way without delivering a fragile solution.

Design Pattern - Inspecting and traversing the DOM in the dataLayer

Take a look at the contact form on http://www.conversionworks.co.uk/contact/:

It’s a simple form but it’s a key outcome for the site. Tracking the form usage and performance is important - the need to measure this form was easily apparent at the design stage so it’s been built to be measured.

!97

Page 98: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

We’re really interested in focus events on each field. Our GA data has shown us that users may click on the first field but they often tab through the rest of the fields. We can’t rely on click tracking alone for accurate measurement. This is a demonstration of thinking through the logical system design - considering the nature of the user interactions with the interface and how data capture needs to cater for all types of interaction.

We’ll address the need to have a focus listener in the next section. First, we’ll see how we can inspect and traverse the DOM using the dataLayer from a click event. The same technique will be useful for the focus event as we will see.

Perform these steps:

1. Publish the container 2. Reload the page 3. Click on a form field 4. Open a javascript console (Developer Tools in

Chrome is fine) 5. Inspect the dataLayer

Typing dataLayer; into the console and hitting return will show the current dataLayer:

The last object in the list is the click event - let’s take a closer look by clicking on the arrow icon next to the object:

!98

Page 99: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!

We can see the event is a gtm.click event as well as five other pieces of data regarding the click event.

1. The gtm.element that was clicked is an input tag 2. The element ID was ‘name’ 3. It has a class of text 4. There is no target attribute on the tag 5. There is no URL attribute on the tag.

These attributes are standard parts of the data structure that is pushed onto the dataLayer when an auto event click or linkClick listener ‘hears’ a click. This data structure is fundamentally important as we’ll see. Now, let’s dig further into the gtm.element attribute. See the arrow icon next to gtm.element? Yes, there is more to see - click it and see what magic is available:

!99

Event Listeners push a standard data structure onto the dataLayer

Page 100: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!100

Page 101: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!101

Page 102: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!102

Page 103: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Wow - this is what is technically known as a shit-load of data - a lot of magic has happened here. Rather than exhaustively describing potential use cases for each facet in this list, consider a use case specific to the context of the form field click.

We need to ensure the element that the dataLayer event pertains to is in fact a field in a form, it’s the field and form that we’re interested in. How do we do this?

The gtm.element attribute for the clicked element contains an attribute of ‘form’. This form attribute has an ID that can be inspected. If the gtm.element does not have a form attribute, we can ignore the click.

First, addressing dataLayer version 2 variables in GTM can be done using the simple notation gtm.element. In the console, life is a bit different. We first access the element in question in the dataLayer by popping it off the dataLayer into a convenient variable in the console:

fieldClick = dataLayer.pop();

Now we can see, access and explore the element:

!

Rather than accessing gtm.element as we would do in GTM, we need to use a different notation to query the object. We know we need to access gtm.element inside the object so we use this approach:

!103

Page 104: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Now, we want to access form inside gtm.element:

Finally we can check the form ID:

Having inspected the DOM through the dataLayer in the JavaScript console, we can then apply this technique in a trigger and variable in GTM.

These techniques enable native DOM traversal and introspection with no need for jQuery selectors, hence there is no 3rd party library dependency and no cross browser compatibility requirement.

Whilst this is a powerful technique, as discussed earlier, exercise a degree of caution in terms of how far across the DOM you wander. Long hikes through many elements will introduce fragility and brittleness due to the risk of future changes breaking the solution. The key to this example is the implied field/form relationship. This transcends normal markup relationships. Form field and form tags are related through the form attribute on the field element, hence, the hop from field to form is not subject to the usual DOM journey making it far more appropriate and safer.

!104

DOM traversal and introspection using the dataLayer is simple and safe but use caution

Page 105: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Design Pattern - Extending auto event tracking - when, how and why

Casting our minds back to the previous example of the contact form on http://www.conversionworks.co.uk/contact/ We’ve looked at how we can use introspection by navigating the gtm.element after a click but auto event tracking only allows us to track clicks out of the box and not focus events. The temptation is to measure focus events using a technique something like this:

jQuery(‘input’).focus(function(e) { e.preventDefault(); _gaq.push(['_trackEvent', ‘Contact Form Field', 'Focus', ,jQuery(this).attr('id'),0,false]); });

This will fire a GA event on a focus event firing but there are a number of techniques in play here that need careful consideration:

- Think very carefully when using Custom HTML tags - _gaq.push in a Custom HTML tag

This assumes the tracker name is blank and will not behave as expected if it isn’t Migration from Classic GA to Universal can be long, risky and prone to error

- 3rd party script (jQuery) dependency - This tag is very specific - the solution does not scale - No gtm.element structure pushed onto the dataLayer

!105

Choose techniques carefully. Weigh up pros and cons before setting in stone

Page 106: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Not all GTM implementations allow custom HTML tag usage - these tags can be blacklisted quite correctly in certain circumstances.

Coupling the custom HTML tag to a specific usage of _gaq.push is poor practice. The effort and complexity of an GA tag config change is increased substantially when tracking tags are implemented using custom HTML. Imagine this situation magnified a hundred times - this mess is best avoided.

Furthermore, this example assumes an unnamed GA tracker has been employed. If a tracker name has been used, this tag will essentially fail. Tracker names can also change building in even more maintenance effort and risk.

Worse yet, if no tracker name is specified, you may not be able to determine the tracker name used by GTM. You could employ _gat._getTracker('UA-6784326-1'); ensuring that you use a variable to extract the correct UA ID but this is merely dressing the wound rather than fixing the issue. Google recommends not naming your GTM tracker . 20

The tag uses jQuery. This will tightly couple your tracking solution to a 3rd party library. This can add extra weight, complexity and removes your control over the library functionality especially if the version of the library is delivered and managed by a 3rd party. These are all ingredients for an unpalatable recipe.

https://support.google.com/tagmanager/answer/3281077?hl=en-GB20

!106

Page 107: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Building such a specific solution, as we will see, requires a tag or set of tags for each tracking use case. A smarter, more general tag offers a highly scalable and easier to maintain solution. Fewer tags to manage is better - always.

Finally, and of massive importance, the lack of the gtm.element object on the dataLayer means that browser neutral and library independent DOM traversal and introspection is no longer possible. The rich data exposed in the gtm.click object is not present here. The solution architecture is fragmented and incoherent.

Ideally, our solution will be browser neutral, not depend on a 3rd party library and will deposit focus event data in the dataLayer that allows gtm.element usage.

Having said earlier that customHTML tags are undesirable, I’ll risk contradicting myself by starting with a customHTML tag for our solution.

Custom HTML tags are not ideal for use in every situation. Building the entire GTM solution based on custom HTML tags is a poor solution. Used intelligently and appropriately, these tags can be powerful friends.

The first part of our custom HTML tag was written by and documented by Google : 21

https://developers.google.com/analytics/devguides/collection/analyticsjs/21

events#crossbrowser!107

Page 108: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

function addListener(element, type, callback) { if (element.addEventListener) element.addEventListener(type, callback); else if (element.attachEvent) element.attachEvent('on' + type, callback);}The second part of our custom HTML tag will find all the input tags on the page using document.getElementsByTagName. We iterate through each element and call addListener to add the focus listener.

var myInputs = document.getElementsByTagName('input');inputIndex=myInputs.length;while(--inputIndex >= 0){ addListener(myInputs[inputIndex],'focus', function(){ customEvent = { "event": “gtm.focus", "gtm.element": this, "gtm.elementClasses": this.className, "gtm.elementId": this.id }; dataLayer.push(customEvent); }); };

You can pass different event types to addListener. Look at the list of potential event types for an element in the gtm.element object. They’re all prepended with the word ‘on’:

!108

Page 109: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

onabort onerror ondurationchange

onbeforecopy onfocus onemptied

onbeforecut oninput onended

onbeforepaste oninvalid onprogress

onblur onkeydown onratechange

oncancel onkeypress onreset

oncanplay onkeyup onresize

oncanplaythrough onload onscroll

onchange onloadeddata onsearch

onclick onloadedmetadata onseeked

onclose onloadstart onseeking

oncontextmenu onmousedown onselect

oncopy onmouseenter onselectstart

oncuechange onmouseleave onshow

oncut onmousemove onstalled

ondblclick onmouseout onsubmit

ondrag onmouseover onsuspend

ondragend onmouseup ontimeupdate

ondragenter onmousewheel onvolumechange

ondragleave onpaste onwaiting

ondragover onpause onwebkitfullscreenchange

ondragstart onplay onwebkitfullscreenerror

ondrop onplaying onwheel

!109

Page 110: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This list is from one tag. The onclick and onsubmit events shown in the table are shown in green as we have native support for them in GTM. The onfocus event is shown in yellow as that’s what we’re heading towards.

When the event fires, we don’t call _gaq.push. We want to populate the dataLayer with the event data. We can share the data exhaust from the event with all connected systems through this messaging conduit using the same techniques employed by Google in GTM.

The customEvent data structure allows us to populate the dataLayer in exactly the same way as native auto event tracking. We specify the event name as gtm.focus. We use the dataLayer v2 style as a convention in keeping with the existing auto event tracking event notation. The element is easily set as ‘this’ - the element that was listening for the event. The classes and ID are set using this.className and this.id.

Our custom HTML tag does a fine job of pushing the focus event data onto the dataLayer:

!

!110

Reuse existing Google code in GTM extensions

Page 111: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The beauty of this design pattern is in the preservation of gtm.element in the dataLayer. Even though we have added a listener for our own event, the end result is exactly as per the native listener. New resources working on the project will see familiar behaviour and functionality resulting in getting up to speed on the project sooner. Existing resources will be able to use the custom listeners as if they were native.

In the event that Google decide to natively support more listeners, the refactoring exercise is trivial for this design pattern compared to the ant-pattern. Fewer tags need major surgery - only a native auto event variable needs to be used to replace the custom listener - all other tags that depend on the dataLayer output don’t need to change.

A word of caution at this point. Be aware of fields that use auto-focus. These will still fire events. An extra listener - a tab listener can push events to the dataLayer in the event of a tab press - only fire events in the event of a genuine tab to focus.

!111

Custom listeners function as if they were native GTM listeners

Refactoring effort is reduced

Page 112: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

function checkTabPress(e) { e = e || event; var activeElement; if (e.keyCode == 9) {//tab was pressed - push to the dataLayer }}var body = document.querySelector('body');body.addEventListener('keyup', checkTabPress);

We can take the listener model outside the scope of standard events and into custom events. For example, tracking a YouTube video player…

There are a number of examples of YouTube player tracking GTM custom HTML scripts, a selection are listed in the suggested further reading section.

The mechanics of tracking YouTube players are dictated by the player JavaScript API. The main takeaway is to employ the customEvent data structure to push the player events onto the dataLayer in the standard fashion:

customEvent = { "event": "gtm.video", "gtm.videoTitle": thePlayer.videoTitle, "gtm.videoAction": thePlayer.actions[0].actionname, "gtm.videoActionVal": thePlayer.actions[0].mainval, "gtm.videoActionOptVal": thePlayer.actions[0].optvalue};dataLayer.push(customEvent);

!112

Page 113: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 8: Form data capture best practices

Summary

Progressing from basic page and click tracking design patterns, this section covers a specific type of page - the form. Forms are often used on sites as part of a checkout or sign up process - they usually represent some sort of key user interaction. Being part of a key user interaction requires a high quality data exhaust. This chapter equips you with solutions that will enable highly valuable form usage data to be captured properly, legally and cleanly.

This chapter explains how combining form interaction GA data with other data sources such as ClickTale or HotJar can guide the reader to make highly optimised forms based on insights from user interaction data. The first challenge is to correctly implement form instrumentation. As this will become a common task, using these design patterns becomes more of a priority:

- The post URI - Tracking form interactions in more detail - Combining extra data sources

!113

Form measurement is a specialised hybrid of page and click tracking

Page 114: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

In the chapter on advanced user interaction tracking we explored techniques to extend auto event tracking to record form field focus events rather than just clicks.

There’s more to tracking a form than just focus events on fields and the focus event is not always appropriate to use. There are other types of fields, check boxes, drop downs and submit buttons for example. Additionally, the form needs to be submitted. Of course, without the submission there is no conversion! Capturing the form submission can require more sophisticated techniques depending on the use case and form implementation. We’ve seen potential issues regarding AJAX forms, we’ll recap that technique as well as dealing with other interesting and challenging form scenarios.

Perhaps you’d like to record certain field values that are submitted by users on the form? You can but you need to choose which values to record very carefully to avoid legal issues.

!114

Page 115: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Submitting a form

We’ll start with the ideal scenario: a basic form posts to a new page with a new URI on the current domain.

Tracking the form submission is a straightforward task of using Auto Event Tracking.

GTM will simply listen for submit events on the pages specified by the trigger and will push a gtm.formSubmit onto the dataLayer. This event can be consumed and used to fire tracking pixels as required.

Avoid unnecessary instrumentation

This ideal scenario has little need for form submission tracking. Rather than decorate the pages with redundant instrumentation, configure a goal in Google Analytics to track the form submission.

Tracking the submission and firing a virtual pageview adds nothing to the data capture in this instance but there are cases where capturing the form submission is essential.

Non-standard forms

We’ve previously covered an example where the dataLayer was populated with a custom event to indicate that a form that posts to itself has been submitted. In this scenario, our contact form is presented on /contact and would post to

!115

Tracking simple forms is natively supported by GTM

Page 116: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

/contact. Not having a unique pageview for the post response prevents the goal funnel from being configured in GA.

Given that form submissions generate a dataLayer message (gtm.formSubmit), this enables the form submission to be tracked regardless of the page URI. Surely you can just fire a virtual pageview or event using the gtm.formSubmit event in the trigger?

Hang on a moment though, a form submission, like a link click is standard browser functionality and we’ve already seen that we need to make sure the tracking pixel is sent correctly before the browser is allowed to respond to the user action.

To cater for standard browser behaviour, the form submit trigger supports the ‘Wait For Tags’ functionality just like the link click trigger.

This is an important setting. In this scenario where a form post causes a page transition, the best practice is to use ‘Wait For Tags’ to ensure the utm.gif or collect request has been made successfully before allowing the submission to happen.

Of course, you specify a sensible timeout period to wait before proceeding in case the response is not forthcoming in a timely manner. You can’t have users hanging around forever so the suggested default wait time of 2 seconds (in milliseconds) is a realistic starting point.

Choosing to wait longer than 2 seconds will require notifying the user that the submission is in progress. Don’t leave the user hanging without letting them know that their form submission is in progress.

!116

Page 117: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Human processor model or MHP (Model Human Processor) is a cognitive modelling method used to calculate how long it takes to perform a certain task. 22

MHP has been used in studies to show that users typically 23

perceive an instantaneous response to an action to take less than 100ms. Anything from 300ms to 1000ms is perceived as a delay. If your wait time can extend beyond 1 second, consider rendering an immediate response to inform the user.

Not using a wait time is likely to result in data loss and inaccuracy.

Another sure route to inaccuracy is to fire a GA tag based on the gtm.formSubmit event when the form has not submitted due to validation errors. Stopping the browser default action (submitting) with any custom javascript can also be trapped to ensure only valid form submissions are tracked using gtm.formSubmit.

Using Check Validation is good practice but if any custom javascript interrupts the default browser action for any reason other than trapping validation errors, the tag will not fire when in fact it should. Inline or unobtrusive scripts on links and

https://en.wikipedia.org/wiki/Model_Human_Processor22

https://www.youtube.com/watch?v=YV1nKLWoARQ23

!117

Let the user know the form is submitting if the form submission has a noticeable delay and you use a long 'Wait

For Tags' timeout

Page 118: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

forms are likely to deliver unexpected and unpredictable behaviour.

Which form has been submitted?

Is this an obvious question? If you have multiple forms on the page, you can track the submission event but how do you know which form has been submitted?

Assuming you have adequately decorated the form markup with appropriate meta-data, the gtm.elementId in the gtm.formSubmit event will contain the form ID. We can see this in the dataLayer using a Chrome Extension called dataSlayer . dataSlayer exposes instances of the dataLayer 24

from each page in a journey. So, having submitted a form, we can see the dataLayer details:

https://chrome.google.com/webstore/detail/dataslayer/24

ikbablmmjldhamhcldjjigniffkkjgpo!118

Avoid changing the default browser behaviour with custom JavaScript

Use multiple data points to to be certain which from has been submitted

Page 119: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Any Google Analytics event or virtual pageview will be able to use this meta data to record the identity of the submitted form. Additionally, and in a less ideal world, a click event handler will also record the click on the submit button:

Using the button click event in isolation is not good practice. With the available markup decorations and auto event handlers we have varying degrees of good practice to track form submissions:

Using the gtm.elementId from the button click and form submit in combination with the gtm.formSubmit and gtm.click events offers the most certain method for correctly identifying the submitted form. Not using the full suite of IDs and event handlers introduces a tangible risk of data loss or incorrectly tracking form submissions in the case of validation errors.

The events and IDs need to be combined in one trigger in order to fire a tag based on a sequence of events. Wait a

gtm.click gtm.formSubmit Form ID Submit button ID

Best practice X X X X

Okay X X X

Not good practice

X X

!119

Page 120: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

minute, how can one trigger respond to multiple events? GTM is event based but only one event can fire a trigger though…

With reference to a technique originally published by Simo Ahava the button click is captured using a custom HTML tag 25

pushing a variable onto the dataLayer:

<script type=“text/javascript"> dataLayer.push({'contactButtonClicked':'true'});</script>

The trigger used to fire our form submission tag will use a combination of the event, the form ID, and the contactButtonClicked variable.

The exception to this scenario is where multiple forms are rendered inside one form tag.

Submit buttons need to be decorated with ID attributes in order to determine which form has been submitted. Our table of form submission best and worst practices now looks like this:

gtm.click gtm.formSubmit Form ID Submit button ID

Best practice X X X X

Okay X X X

Not good practice

X X

.NET forms X X X

http://www.simoahava.com/analytics/form-tracking-google-tag-manager/25

!120

Page 121: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Yes, unfortunately the case of the multiple forms in one form tag is usually found on .NET pages.

Extracting form values

So far we’ve discussed tracking form interactions - field focus, change or click and form submission. What about the actual values? Can we record those in Google Analytics? Should you track the field values in Google analytics? It’s technically straightforward to capture the values but the ‘should’ question requires two answers:

- What business reason is there to capture field values? - Is there legal justification to capture field values?

Tracking binary or discrete values such as check box or radio button answers in a survey may be a valid justification. Free text fields are likely to contain unreliable or unsafe data. Unless you can control the nature of the input, think very carefully before choosing to capture the data

- Always treat user input as tainted and potentially dangerous. - NEVER record personally identifiable information (PII) in Google Analytics

The last point is crucial to the safety of your data. Recording PII data contravenes the GA terms of use and your data may be deleted if it contains PII.

Assuming you have identified legal, safe and meaningful fields to capture values from, the value extraction can be done relatively easily.

!121

Page 122: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

When the form is submitted, the fields are be exposed as input attributes of the gm.element object found on the dataLayer in the gtm.formSubmit dataLayer message:

Using a variable such as:

gtm.element.Field Index.value

Change the field index as appropriate. There is very little DOM traversal here so the technique is quite safe. Use a class on the field to ensure only fields with a class of ‘dataExtract’ are used for Google Analytics data.

!122

Page 123: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 9: e-Commerce tracking

Summary

This chapter is focussed on using design patterns to solve for a particular type of conversion tracking. This will literally help you extract the maximum value from your Google Analytics data using transactional data. Using transactional data in Google Analytics enables you to monetise your site - see where the value to the business really is.

In order to get transaction tracking right, this chapter will guide you through a range of key areas that are often subject to anti-pattern usage:

- Transaction dataLayer usage - Enhanced Ecommerce - Antipattern - DRY(TD) - Don’t repeat your transaction data - Correct usage of e-commerce fields to supercharge transactional reporting

Failure to measure the commercial performance of a site normally means drastic over or under counting has happened. It’s important you understand that penny level precision is never going to happen but transactional data that is accurate to a known and acceptable degree is good enough and is vital to understand business performance.

!123

Getting ecommerce data right is a fundamental business requirement

Page 124: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Having discussed tracking outcomes and conversions using GTM and GA, a very special case of a conversion is the transaction. This is often the reason for having a site - to sell products or services and generate profit for the business. Talking of money and profit as a measure of site performance is really dealing with the core of the business.

For this reason, getting transaction tracking right is exceptionally important.

This does not mean it is necessary to spend more time on the technical solution, however. It means the time needs to be spent on the design of the technical solution such that the simplest and most robust solution is implemented.

Technical solution robustness leads to more accurate data. A brittle solution will over or under count transactions. Brittleness and complexity go hand in hand. Inaccuracy follows along in hot pursuit.

Common issues with ecommerce data are - repeated transaction tracking resulting in overcounting - not tracking transactions due to javascript errors resulting in under counting - fake transaction tracking - sparse data reducing the effectiveness of the data

!124

The quality of your data (especially ecommerce data) is a reflection of the robustness of your system design and

implementation

Page 125: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The transaction dataLayer

Tracking and handling javascript errors was covered in the section on reliable dataLayer implementation. The health of your ecommerce data is particularly dependent on a solid and reliable dataLayer.

Google have documented the dataLayer variable names to use for GA ‘old’ ecommerce transactions and Enhanced 26

Ecommerce data . 27

Don’t argue - use the names as shown in the documentation.

Pay careful attention to the values used in the dataLayer. Just because the TMS is a smart piece of kit does not allow sloppy value usage. The type of data to use is clearly described and demonstrated in the Google documentation.

Make sure you really use the fields. The quality of your transactional data depends on the correct and full usage of the fields whether using Enhanced or Standard commerce transactions.

https://support.google.com/tagmanager/answer/300259626

https://developers.google.com/tag-manager/enhanced-ecommerce27

!125

Use the standard appropriate dataLayer variable names which ever transaction technique you use

Don't stick to them bare minimum of transactional fields – enrich your data as much as possible

Page 126: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The practices discussed so far with reference to dataLayer implementation and usage are of the greatest importance in the context of transactional data.

Enhanced Ecommerce

Announced in 2014, Enhanced Ecommerce was a major upgrade to Google Analytics. GA now sports not only transactional data also related shopping behaviour data. Exploit this key feature with the support of GTM.

Unlike classic transaction tracking, Enhanced Ecommerce (EE) does not use a specific tag. The EE data is sent to GA as part of the payload of conventional tracking tags - page view or event tracking pixels are decorated with shopping behaviour data. Having chosen a tag to use as an EE tag in GTM, you need to decide how GTM will extract shopping data from the website. There is a choice of mechanisms that can be used.

The most obvious and preferable choice is to render the data in the dataLayer in the <head> for use by GTM when it loads. This approach results in the least amount of complexity added to GTM as the standardised dataLayer variable names are automatically recognised. No new variables need to be created in GTM.

This is a good thing - the measurement layer is not responsible for managing transactions other than being a conduit for the data.

!126

The quality of the transactional data is the first concern

Page 127: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The system responsible for generating and managing the transactional data is also responsible for delivering this data in the appropriate format to GTM through the dataLayer.

This responsibility includes ensuring correct usage of published variable names and ensuring the data is rich and complete. Where EE fields are available, use them. If you don’t have complete data available at the time of transaction, consider using Google Analytics data upload to ensure your shopping data is as complete as it can be.

The other mechanism available to get EE data into GTM is using a custom JavaScript variable. This is a more complex route requiring more software to be built in GTM. Why might you choose this route?

- What if your receipt page is an AJAX page? - What if you can’t render the dataLayer at all?

If your shopping receipt content is returned by an AJAX call you can use the History listener to fire a non-interaction event or virtual page view with the data pushed onto the dataLayer.

If you can’t render the dataLayer on the receipt page you will need to use a custom JavaScript variable to call a function to return the ecommerce object. Ensure the standard dataLayer syntax is used in the ecommerce object that is returned.

The first approach described using the dataLayer is preferable due to architectural correctness and all round GTM cleanliness. As mentioned earlier, transaction data

!127

Rich and complete ecommerce data is one of your most valuable data assets.

Page 128: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

presentation is not the responsibility of the measurement layer. The data being presented to the user is the same data that is to be presented to GTM and only the format and syntax differs. The presentation layer presents the data correctly to the user on the receipt page so there is little reason why it can’t be done for GTM in the dataLayer.

Using the custom JavaScript variable is not preferred purely in terms of the extra complexity in GTM. There is temptation to build logic and processing into the variable and is often the case where changes to the presentation layer or back end are hard, expensive, or slow.

!128

You don’t ‘fix up’ your content data using GTM so don’t ‘fix up’ your transactional data using GTM either.

Page 129: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Anti-pattern - tracking the same transaction multiple times

The Google documentation for transaction tracking with GTM suggests using a trigger to fire the transaction based on the page path matching your receipt page or ‘thank you’ page.

There is a fundamental flaw in this technique where transactional data is concerned. The risk with this type of trigger is that every time the thankyou.html page is reloaded the transaction tag will fire. This will result in the transaction being repeatedly fired into Google Analytics. This is situation needs to be, and is easily avoided.

When the transaction tag fires we can use the hitCallback functionality to remember that we’ve fired a certain transaction by setting a cookie to contain the IDs of the user’s transactions. Note, this is hopefully many and so all transactions need to be recorded in the cookie.

The potential flaws here are

- The cookie may be deleted - The user may use a different device or browser - The cookie could grow too large

The multiple browser and cookie deletion issues could be resolved by tracking the user ID and (re)setting the cookie when the user logs in but the cookie size issue is harder to resolve cleanly.

!129

Page 130: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

However, whilst we acknowledge the limitations of this approach, this is a useable technique to demonstrate that the issue can be fixed.

But it serves only to demonstrate what the site should do. The site should be capable of knowing a page is being reloaded and that the transaction has fired already.

All parties involved in designing and building the system need to be aware that the site should not render a transaction dataLayer more than once.

Fixing this issue in the site software is beneficial because:

- The business logic, presentation and measurement layers remain focussed on their specific function - Complexity is reduced - The software stack is cleaner and easier to maintain

!130

Page 131: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 10: Social

Summary

Use of Social buttons is an inevitability for many businesses. Whatever your social strategy, however you intend to exploit or extract value from social media networks and channels, understanding how to use GTM in the context of Like, Share, Pin, +1 and Follow buttons is worthwhile.

The two main aspects of GTM involvement with social actions that will be discussed here are:

- Implementation - Measurement

!131

Page 132: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

You are probably aware of things like these:

You are hopefully, also aware of the social reports in Google Analytics:

The frequent challenge is to capture data regarding social button usage on the site and deliver high quality reporting in the Google Analytics social reports.

This is not such a trivial challenge. These ingredients are normally a recipe for an anti-pattern feast.

Following the system design process will take you through the logical thought process of first deciding what to measure and then choosing how to implement the measurement.

The strange thing is that social network buttons seem to emit a mysterious aura that changes behaviour in people and reverses this order. This results in an approach of ‘Get the buttons on the site’ and then ‘Figure out how to track the clicks’.

This is wrong.

First decide what to measure by thinking about the social actions that are valuable and relevant to your site. Then

!132

Page 133: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

investigate the options for implementation and choose the correct approach for your site.

Measurement Start with the assumption that your marketing team have briefed the project stakeholders on the social media strategy. It will be clear to everyone that the social channels that are to be used will have been decided based on solid business reasoning.

Now you can decide on the potential measurements offered by the social buttons. This will be a discrete set of potential user actions that need to be recorded in Google Analytics. Are your business goals focussed on reach? Think about measuring shares. Are you growing your fan base? Think follow and like actions. Do you want your product images seen by as many eye balls as possible? Think pin actions. Ensure your measurements are aligned with your strategic goals.

Quite simply, the correct Google Analytics metrics to use are the Social track type - not events. Make use of the correct GA reports and correct measurement types. Events could be used and often are but why choose an inferior product? The implementation challenges are essentially the same but the data quality and potential insights delivered by event reports are weak compared to the dedicated social reporting in Google Analytics.

Implementation

The first consideration is to think how the social buttons get rendered on the site. Here’s a golden rule to help with this

!133

Page 134: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

thought: GTM is not a content management system. Using a custom HTML tag to render your social buttons is ill advised.

Later, we’ll discuss how custom HTML tags can be the cause of significant trouble. Usually as a result of a poorly written javascript and/or the inclusion of a 3rd party javascript library by the custom HTML tag.

In terms of sound architectural practices you should respect the separation of concerns and don’t mix the function of architectural layers. Rendering content such as social buttons is best delivered by the site presentation layer, not a custom HTML tag in the measurement layer.

The choice that needs to be made on the presentation layer is whether to adopt a social plugin, to render the buttons using scripts provided by the social network or to grow your own scripts.

Scripts provided by social plugins and by social networks to implement the social buttons both introduce dependencies so both are on equal footing in that respect.

Depending on the Social Networks you’re using, choosing the plugin route may be more palatable if you’re using a large number of buttons.

Social Plugins Currently, most social plugins have poor support for dataLayer usage and will require click event handlers to be used to push dataLayer events when buttons are clicked.

!134

Page 135: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Social Networks If your Social Network channel coverage is slight, using the scripts provided by the social network may be the most appropriate choice. They will still need some modification in order to push dataLayer events when buttons are clicked

Grow your own Engineers may choose to use existing button image assets but build the button action and measurement functionality completely from scratch according to house styles and standards.

Given the degree of control and reduced dependencies on 3rd party scripts, this may be a valid choice.

Having chosen the appropriate implementation, assuming the markup is solid and measurable, the tag building exercise is trivial.

Measurement

As far as measurement is concerned, the required end result is to push object literals onto the dataLayer encapsulating the social action in order to fire the Google Analytics social tag using a click event in the trigger.

From this quick exploration of the current Social Button landscape, two key ingredients required to deliver this solution are clear to see:

1: Scripts are available to render the social buttons so that they look good and function correctly.

!135

Page 136: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

2: There is support for the Google Analytics Social tag in Google Tag Manager.

Unfortunately there is little cohesion between GA/GTM and social buttons. Buttons are easy to display but measurement support is light and needs engineering work to be achieved.

The main lesson to apply from these points is to design and build a solution that works for you right now and will not be a major engineering exercise to rebuild should social buttons decide to use the dataLayer or GTM social listeners become available.

Implement your social buttons and build the measurement around them so that the measurement is easily refactored with least risk and effort.

!136

Page 137: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 11: Onsite search

Summary

A special instance of the form interaction use case is the onsite search scenario. Studies show this piece of functionality is frequently executed badly and measured poorly despite offering significant commercial value to site owners. Typical anti-pattern usage results in poor quality or no keyword data, no usage pattern data (where and when searches happen) and no ability to quantify the commercial value of onsite search.

Search keyword data is becoming a scarce resource so any potential keyword asset is extremely valuable, highlighting the need to execute and measure onsite search correctly.

Addressing the design patterns in this chapter helps you to understand the best practices for measuring onsite search usage and maximise the returns from it using Google Analytics and Google Tag Manager.

- Tracking the search term - Normal searches - Suggested searches - Anti-pattern - not exposing search terms to Google Analytics - Tracking the search category & filters - Anti-pattern - Preventing the blank search scenario - Tracking search result volume - Tracking search result clicks

!137

Onsite search can deliver >300% higher conversion

Page 138: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

To explore the scope of onsite search measurement we need to perform some searches, understand what the data exhaust is comprised of and how it can be of value.

This is a good example of how measurement and data are included in the system design exercise.

For example, start with a simple search on Amazon for any books related to Google Tag Manager:

! What happens when this search is performed? As I type ‘Google Tag Manager’ auto suggest items appear:

!

Clicks on the automatically suggested items need to be tracked as well as which suggestion was clicked for a given search phrase.

As the search is completed and submitted, the search results are presented on a new page. We have a new URL and new page content that we can use to extract data regarding the search we just performed.

!138

1st challenge: understand the potential for onsite search measurement

Page 139: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

From the URL we can to determine the search terms and the search category that were used. From the page content we can to determine the number of search results presented and track any further search related behaviour.

In our example, currently, 9 results are presented along with a range of search filters to help me find just what I’m looking for:

!

Choosing to refine the results to only those in the ‘Computing & Internet’ section, the page updates and the URL changes again. A final refinement to the search results before I buy reveals that including only 4 star rated books updates the page and URL again.

In summary, we want to look at four components of the search journey data exhaust:

1: The search - What was the search phrase used? - Was there a search category used? - Were any automatic suggestions clicked? - What page was the search performed on?

!139

Page 140: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

2: Search results presentation - How many search results were presented? 3: Search results actions - Were any search refinements made? - Which results were clicked 4: Post search actions

We will see that the Amazon example is particularly clean and was clearly designed to be measured. We can extract all our data exhaust from the post action URLs and on page data (ideally rendered in a GTM dataLayer).

Illustrating anti-pattern usage in contrast will show how easy it is to miss opportunities to easily and cleanly capture vital data points resulting in fragile system compromises.

!140

Page 141: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Capturing the search term and search category

In our earlier example, having performed a search we can parse the resultant URL to extract two key pieces of information using two query string variables:

- url - field-keywords

The url parameter is used for the search category and the field-keyword is used for the keyword. These parameters are easily plumbed into Google Analytics as part of the standard onsite search tracking configuration.

This pattern is widely observed but what happens when it is not? If a POST method is used on the search form, no search keyword or search category data will be present on the querystring. This prevents Google Analytics from being able to see a search.

Is the choice of using a POST method so odd though? After all, the norm is to use a POST method when marking up a form. What do we do if the search term and category are not exposed in the search results URL?

Advocating the use of the dataLayer to fire a virtual pageview for use in Google Analytics tracking is a naive hack that avoids fixing the site in favour of using the measurement layer to fix the site.

!141

Use the GET rather than POST form submit method for search forms

Page 142: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The root cause of the issue is the incorrect choice of form method and this should be the fix that is applied.

It will be useful to reread when to use a GET method and when to use a POST method - this revision will show that 28

the GET method is the most appropriate use for the search form for obvious reasons.

Reasons to use the GET method

- GET requests can be cached - POST requests are never cached

Caching is desirable as search queries can be computationally expensive. All performance uplift opportunities are welcome.

- GET requests remain in the browser history - POST requests do not remain in the browser history

Repeating a search is wasteful. Allow the browser cache to work for you.

- GET requests can be bookmarked - POST requests cannot be bookmarked

Allow users to save searches.

- GET requests should never be used when dealing with sensitive data

Search queries are generally not considered sensitive.

http://www.w3schools.com/tags/ref_httpmethods.asp28

!142

Page 143: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

- GET requests have length restrictions - POST requests have no restrictions on data length

Limit the length of the search phrase to a reasonable limit. Most sensible searches will happily fit into this limit. - GET requests should be used only to retrieve data

This is exactly what a search is doing - requesting search results.

Auto-suggest clicks

Look at the markup used when the Amazon automatic search suggestions are shown:

<div class="suggest_link suggest_link_over" id="issDiv0" style="cursor: default;"><b>google </b>nexus 7 <span>in <span class="sx_category_name_highlight">Kindle Store</span></span> </div>

The automatic suggestion is wrapped with a div that sports the class ‘suggest_link’ making clicks on this element easily trackable. Using a trigger to capture a click on an element with a parent with this class can be used to fire an event. The element id shows the index of the auto suggest link that was clicked. A variable returning this value can clean the data to present an integer for use as an event value. This value can be used to see the average index of an automatic search suggestion that is clicked on a per search keyword and per suggestion basis. This is golden performance data for auto suggestion functionality optimisation.

!143

Page 144: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Ideally the automatic suggestion will be rendered as a link which means that the ‘wait for tags’ functionality can be used. The click can be captured and used in a trigger to fire the tracking pixel while ‘wait for tags’ then allows the browser to take the user to the required page only once the tracking pixel has fired.

This is completely standard browser behaviour and uses the maximum built in functionality of GTM - an ideal situation.

Question: If an automatic suggestion is clicked, should this be recorded as a search?

Depending on the business requirements, this action can be recorded as an event or a search using a virtual pageview.

To record it as a search, the resultant page URI will contain the querystring parameters url and field-keywords to enable the interaction to be recorded as a search. The search keyword will be recorded using the term that was typed before the click - not each keystroke during typing.

Similarly, the values can be used in an event tag rather than a virtual page view.

Search result volume

When search results are presented, the accuracy and precision of the search results will have a bearing on the quality of the user experience. If a user searches for red widgets, are only search results for red widgets presented? If there are 5 red widgets in the product inventory, are all 5 red widgets presented? Are only 5 red widgets presented in the search results?

!144

Page 145: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Recording the number of search results shown for a given search is straightforward. The search keyword will be exposed in the URL and the search result count in the dataLayer as shown below. This data can be extracted using two variables for use in a Google Analytics event tag to record the result count for a given search.

window.dataLayer = window.dataLayer || []; window.dataLayer.push({ ‘event':'searchResults', 'searchResultCount':9 });

Note that even in the event of zero results being shown, the searchResultCount value should be rendered as 0 - the keywords used that return no search results are of particular interest. These use cases are failure modes for the search functionality - these need to be recorded as they are highly actionable.

Search results clicks

Understanding which search results users click on will answer important questions and reveal key insights into how well onsite search is performing.

This can be achieved using a Behaviour Flow report or the navigation summary report in Google Analytics. A sequence based segment could be used also but all these techniques are too reliant on the skill of the analyst in extracting the data and being able to present the insights extracted from the data.

!145

Page 146: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This is an instance where recording an extra click can yield data that is simpler to interpret and present. There is value to an organisation in making the data more democratic and accessible.

Whilst recording the click on the search result increases the data volume, the quality of the data that is captured merits this trivial increase. For instance, the Amazon search results are presented such that the index of the search result is part the ID attribute of the element wrapping the search result:

!

Assuming the index of the clicked search result can be determined without having to traverse too many levels in the DOM, the resultant data from the variable can be used in a GA event value.

The average index that is clicked for each search term is now easily apparent in the events report. Similarly, search results that are not clicked will be discoverable using a simple segment. The questions that follow are:

- Which search keywords don’t get clicked? - If so how many? What is the average index? - Why are these results not getting clicked?

These metrics and insights can be considered highly valuable and actionable in terms of optimisation of onsite search functionality.

!146

Data quality beats data volume every time

Page 147: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Failure to record the index of the search result click and the search result volume successfully hides a wealth of detail regarding user behaviour and interaction with a key conversion generator. Given the relative lack of complexity in these measurement solutions, the opportunity presented in these examples has tremendous commercial value.

Post search actions

Having completed a search, users now need to fulfil their intent for being on the site - buying a product for example. That’s the ideal end case. Searching, then buying is a classic behavioural flow but it may not always happen. Users can choose to perform a wide range of actions including but not limited to the following:

- Leave the site - Buy - Create a wish list - Generate a lead - Download a document - Submit a contact request - Perform some action of value

All of these options are of interest to the site owner and analyst. At the heart of this measurement is the need to ensure the original search is captured initially in order to decorate the session with the correct search status. Using the session search status and the built in unified segment ‘Performed Site Search’ enables further analysis and action on this key user cohort:

!147

Page 148: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

! Consider investigating and comparing ecommerce metrics for users who searched against users who did not search to start with.

!

!

Over 20% of users are searching and converting quite well. Not bad, but what else did searchers do? What other goals did searchers convert on?

!

Hmm - lots of login actions for users who searched. How loyal are searchers? Are searchers new users or returning users?

!148

Page 149: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

!

Interesting balance - now consider the alternative - non-searchers

! !

!

A remarkable difference in performance and a clear commercial opportunity.

As far as using search data as a proxy to measure intent, use the keyword data for users who land on the site (from organic search) and then search immediately, as an implied organic search term. Our studies suggest there is a tight relationship between organic search terms and onsite search terms for users who land and search.

!149

Page 150: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Preventing the blank search scenario

What happens when I click ‘Go’ on the Amazon search box without specifying a search keyword?

!

Not a lot. I get returned to the homepage. The user is permitted to search using a blank query. This seems like curious behaviour for a user but a surprising number of sites allow blank searches to happen. More often than you’d think. Yes, it’s the Internet, users do the craziest things!

So, was this a search or not? The typical and unsatisfactory answer is ‘it depends’. You need to make a judgement call.

Deciding on whether this is a blank search or not depends on how you want to handle it - what does it mean to the business? What could happen if you allow blank searches?You can present a manufactured search results list based on your top selling or most profitable products.

It’s a very contrived user experience but if the majority of users are satisfied, then the solution seems valid.

As long as your blank search handling is sound, results in a solid user experience and you track instances of blank searches, then you have a solid business solution. The data exhaust is good quality, the strategic aims of the business have been met and users are happy.

You don’t necessarily need to prevent blank searches. What you do need to do is to handle the use case to satisfy users

!150

Page 151: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

and measure the performance of the solution. Without the measurement, you won’t know if blank searches are happening and how well your solution is performing.

!151

Page 152: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 12: Tracking engagement

Summary

A common measurement anti-pattern is the blog site - a single page site. Due to the nature of the site, the user interactions that can be captured to measure content consumption and engagement are limited. Typical data issues include unrealistic bounce rate and time on site metrics.

These metrics are considered valuable and are frequently taken as proxies for the nebulous engagement quality - a common KPI for the single page or blog site. Whilst such a property is not well defined - there is no metric for engagement as such, using a composition of basic metrics to quantify content consumption is a valuable solution to understand and use, not only for blog site measurement but for pages in general.

Essentially, the volume and rate of content consumption can help to show how users engage with different pages and content areas. The single page site does not deliver multiple pageviews and therefore won’t exhibit any session duration or pageview data.

This short and simple chapter offers the reader a reusable solution for this frequently encountered use case.

Whilst the chapter is titled ‘Blog Tracking’ this design pattern is a robust, highly scalable and reusable technique to employ for any content heavy or media based site.

!152

Page 153: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Bounce rate can simplistically be defined as a single page visit. There is more to a bounce than this description conveys but for an introduction, this definition will suffice. Given that a blog site only has one page, the session will normally only include one pageview and will be recorded as a bounce - wrongly so. Bounce is taken to mean ‘a user who does not engage with the site’ and this may well not be the case. Users will read, scroll, read more, be entertained, informed and satisfied and eventually leave the site. Clearly they were engaged but if they are tracked as bouncers, then they are being tracked wrongly.

Time on site or more accurately, time on page is also strangely hard to measure in the context of the single page site.

Normally, when a user lands on a page, the pageview is recorded in Google Analytics with a timestamp value. As the user navigates to the next page on the site, Google Analytics will compare the timestamp for the second pageview with the timestamp for the first pageview. The time on page for the first page is calculated from this comparison.

Session duration is calculated using the timestamp for the last page that is viewed in the session and comparing it with the timestamp for the first page viewed in the session. As the last page viewed does not have a ‘next page’ timestamp to compare to, exit pages never have a time on page metric.

Blog sites, with single pages, also rarely have an accurately recorded time on page (or session duration). If there is only

!153

Page 154: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

one pageview in a session, there is no other pageview timestamp to compare to.

Hence, an inaccurate bounce rate and time on page leave the blog site owner lacking two key content consumption metrics.

A bounce is actually more accurately described as a session with only one interaction. User interactions can yield Google Analytics tracking pixel requests for

- pageviews - events - social interactions - transactions

If a session sends only one tracking pixel request to Google Analytics, we have a bounce. This is why event tracking needs careful thought as sloppy event tracking can destroy a bounce rate when interaction events are fired instead of non-interaction events. Interaction events can therefore, also be used to help calculate a time on page metric for exit pages and single page sites.

We will see how judicious firing of events after the initial pageview allow a more accurate bounce rate to be calculated along with a representative time on page metric.

!154

Page 155: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Engagement tracking for single page sites

The challenge of addressing the bounce rate and time on page metrics for single page sites in Google Analytics has been tackled well in the past. Notable examples of excellent solutions include a pioneering post by Justin Cutroni and a 29

more recent version by e-nor . 30

The technique shown here is based on the premise of reacting to scroll events. We calculate the current position of the viewport on the document as a percentage of the overall height of the document and fire a Google Analytics event with appropriate values. This version of the solution is GTM based and is independent of any 3rd party javascript library - no jQuery is used.

The example linked below pushes a custom GTM event and a pair of variables onto the dataLayer when users finish scrolling.

The GTM event is used to fire a GA event to record the proportion of the page that has been viewed by the user and the length of time taken from page load to the completion of the scroll event. The non-interaction nature of the event is set to false in this example. It’s very easy to only fire an interaction event if the user scrolls past, say, 50% of the page content. You may decide that only 50% scrollers are properly engaged so only their interaction status will be affected. All

http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-29

analytics-part-1/

http://www.e-nor.com/blog/google-analytics/measuring-page-scroll-in-30

universal-analytics!155

Page 156: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

scroll events will still be measured but the engagement threshold is customised to your requirements. Additionally, the thresholds where the events are fired can easily be changed to suit if 25% increments are too fine or coarse grained. Always be aware of firing off too many tracking pixel requests in a session though. There is a limit of 500 hits per session (not including ecommerce transactions). 31

A boolean flag is set to limit the number of times the event fires and not risk bursting this limit. The event will fire only the first time the user scrolls past a given threshold. There will only by one 25% event per user per pageview.

Events are used rather than pageviews as the average scrolled distance is often a good yardstick to compare the amount of content consumption. Pageviews could be used as an alternative if this data is not required.

Download a container with the custom scroll listener, event tag, trigger and variables here:

http://goo.gl/v9TWdN

https://developers.google.com/analytics/devguides/collection/ios/limits-31

quotas!156

Page 157: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Scroll Listener Tag

The custom HTML tag ‘scroll listener’ is fired on every page - if this is a blog site, there may be only one page. You can also fire the script on any page or a section of pages of your site by tuning the trigger filter.

Scroll Event Tag

The tag that fires the event must have a Non-interaction value of False in order to make the event interactive. The distance the user has scrolled to is set in the value field so this must be an integer.

Scroll Event trigger

The tag is fired when a GTM event gtm.scroll is fired and a valid value for the scroll distance can be extracted.

Scroll Time and Distance variables

The Scroll Time and Scroll Distance variables read the values from the dataLayer.

Scroll Event Data

The data produced in the event report shows the number of scroll events per page along with the average distance scrolled per page and the average time taken to scroll to each increment

The bounce rate and average time on page metrics will now be more representative of reality and hence far more trustworthy and actionable:

!157

Page 158: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Section 4 - Operations

You’ve got a beautiful plan, design and you’re ready to roll. Now implement it perfectly and keep it that way.

!158

Page 159: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 13: Development and debugging

Summary

At this point the you will be aware of many measurement anti-patterns and hopefully will already have attempted to implement instrumentation based on the design pattern and best practice examples.

This chapter helps you step through the engineering task using a methodical, logical and repeatable process to implement the design patterns and best practices. Commonly available tools are used to reinforce and cement a fundamental understanding of the technicalities of website measurement. Whilst not essential, taking your understanding to this level helps clarify the logic behind the design patterns and best practices. The deeper the understanding, the better your decisions will be.

In this chapter we’ll cover:

- Development, Debugging & Testing - Methodology & organisation - The container - understand what the container does - The dataLayer and gtm.js - Developing and testing tags, triggers and, variables - Documentation - Injecting the container on a site that doesn’t have GTM

!159

Page 160: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

Using your internal development teams to build and maintain your own site typically involves the use of a development and testing process. This will be well defined with clear roles and responsibilities. You’ll have access to the right environments to develop and test your tags, triggers and, variables. In this chapter we’ll discuss what, when, where and, how to develop and test - a set of heuristics to use for GTM implementation development and testing.

Another scenario: When a 3rd party team is building your site - either a green field and brown field site (brand new site or site rebuild) how do you go about development and testing the measurement functionality? How does the process differ (if at all) for sites where access to the development and test environments is limited or not possible?

This chapter will cover the need to be organised when developing tags, triggers and, variables and how an organised and structured approach is key to GTM development and management whether building internally or with a 3rd party.

!160

Page 161: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The need for organisation

Obvious statement: Development and testing needs to be organised. The mechanics of debugging and testing will be covered in this chapter but a key ingredient to a measurement project is the maintenance of order and structure in the system and mental focus during development and testing. What best practices can help you?

Having produced the most elegant system design that is strategically aligned to business goal measurement like a weather vane in a prevailing gale, failure to mirror the design quality at the implementation phase is still a possibility.

An important realisation is that in developing any software system, the end goal is to make change. A set of requirements have been identified and need executing, so, you need to fully understand the need for change and the desired outcome before your start the process.

Start with the big picture in mind and don’t lose sight of the strategic goals in the midst of tactical manoeuvring. Think, as you make additions and changes to your container, why you are doing this. Why did you fire up the GTM interface and what is the goal of the change? Are the changes achieving the goal?

When engaged at the detailed implementation level and involved in the mechanics of developing and debugging tags, triggers and, variables, it helps massively to decouple the components in the system where possible and appropriate.

!161

Page 162: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Think in small chunks in order to build a maintainable system. This is one instance where a solid naming convention will help describe the function of a tag, trigger or variable.

Organised GTM Assets

The tags, triggers and, variables you develop are designed and built for a specific site. When managing multiple sites how do you organise your GTM assets for each site? What container organisation strategy should you employ? The Container Administration and Configuration chapter will cover container strategies. When you need to push assets from one container to another you can decouple the function of the tag from the site in question using some simple techniques with lookup table variables. For example, a UA ID Lookup variable enables the container to be used on any environment within the mysite.com domain without having to worry about which GA property ID to use.

Similarly, the thought required to set the correct cookie domain value is reduced significantly by a Domain Lookup variable.

Whilst dealing with a single tag, in a single container, you need to understand the function of the triggers and variables on which it depends. You also need to know which other tags use the same triggers and variables. Solving for a single tagging requirement will ideally not require further changes to other GTM assets. Be aware that this can happen and that this is to be avoided and is made possible by building assets that do one thing and do one thing well. Multifunctional assets will have more dependencies and therefore will be more prone to being affected by changes.

!162

Page 163: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

With this potential scenario in mind, consider the quote below:

The sentiment of modularity and abstraction could be taken to the extreme resulting in a vast GTM implementation resulting in overly specific yet abstract triggers and variables:

- A Floodlight conversion tag per product page - Dumb tags that require management of hard coded values instead of using variables - Deeply nested variables

Employ trigger and variable assets intelligently to implement tags that serve one purpose but are reusable across all instances of the use case.

There is no unit to measure complexity but the right balance will be apparent in terms of the amount of system knowledge required to be mentally internalised before progress can be made.

!163

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction.

Albert Einstein

Everything should be made as simple as possible, but not simpler.

Albert Einstein

Page 164: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

For example, do you want to manage an ever-lengthening list of custom parameters in a Remarketing tag or do you want to let the complexity reside in the dataLayer? Clearly extracting the complexity out of GTM will result in a simpler and easier to maintain tagging solution. If logic is required to decide which values to use in the tag, the presentation and business logic layers will be used rather than the measurement layer. In summary, the choices you make at the design level will influence the degree of effort required and the likelihood of success in development, testing and debugging. Your design choices will help you remain organised and focussed resulting in a solid measurement layer, a performant, accurate, scalable and maintainable analytics implementation.

Developing Tags, Triggers and, Variables - Preview, debug, share

This section isn’t going to cover the manual process of building assets for a GTM container. The Google documentation is quite clear on how to use the GTM front end. Nor is it a review of development procedures and processes - equally well documented though they are, much of the subject matter is not in the scope of this book. The practices described in this section advise choosing the right approach rather than the easy approach.

The power and accessibility of GTM can also be your downfall. The power is in how easy it is to use. The downfall comes with abuse of this power in order to try to run faster than is sensible or safe.

!164

Page 165: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Start at the beginning, before you start any development work, choose the appropriate environment to operate on.

Use the right container

As we’ll discuss later, the preview function is powerful and essential but it is not an excuse to circumvent the develop - test - production cycle. Development can even start on a throw away container before hitting the development container if you’re conducting prototyping exercises or experimenting with new techniques.

Building new assets on the wrong container is likely, at best, to result in lost work at some point or unpredictable functionality at worst which can put production data at risk. Furthermore, maintenance of the version history will be lost or broken.

Follow robust development processed

The high level process shown in the diagram below recommends using the preview function to conduct unit testing. Only once the measurement unit tests pass does a version get created and published. The creation of a new container version must be coupled with version notes. Another point in favour of iterating over smaller changes is the granularity of the version changes will make tracking the evolution and progress of individual tags, triggers, and variables far easier than in large batches.

!165

Don’t start building tags, triggers, and variables on the production container.

Page 166: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Synchronisation of version notes, version names and GA annotations facilitates the development and testing processes.

Completing unit tests, creating a version with the associated notes and version name when publishing opens the environment for a round of QA testing.

Reuse assets

You’ve identified the right container to start work on. You’ve got the change or new asset in mind. Think before you create a new tag, trigger, or variables, what assets already exist that do the required job or at least come close?

Reuse these assets as much as possible. Save time and the risk of finger trouble when creating GTM assets. Asset configuration can get complex very quickly.

Having to recreate lots of standard settings in a tag can take time. You may be working on an existing setup for the first time, or for the first time in a long time so the details will not

!166

Page 167: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

be familiar or your recollection may be rusty. Use the tag copy functionality to save time and effort.

Referring back to naming convention usage, correct usage of a solid naming convention will help promote asset reuse.

Working on a suitable copy saves a huge amount of setup effort and will improve development accuracy.

Repetition of functionality is easy to achieve in an environment where multiple resources are working on a solution. Even if a ticket system is used where tasks are well managed and a process is followed, similar tasks will produce similar results. Awareness of existing assets (using the naming convention again) will vastly reduce wasted effort and a needlessly bloated GTM library.

Use the Copy function as much as possible but do make sure you rename the new asset appropriately and don’t hit delete by mistake!

Debugging using preview and share

Having completed some form of GTM development work, prior to version creation and publication, your changes can be reviewed in a safe environment without impacting other users, testers or developers using the preview functionality.

This is an exceptionally useful tool for development and debugging. Using the GTM debug window in combination with suitable tools such as the Network and console tabs in the Chrome Developer Tool will reveal the details of the requests being sent to Google Analytics by the tags:

!167

Page 168: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The details of these requests are at the heart of the correct functionality of the measurements being fired by Google Tag Manager. Seeing these values on the screen along with the details regarding the tags that have fired or not, why, the dataLayer and variable values enables you to unit test tags, triggers and variables on your site.

Whilst we’re in the console during unit testing and debugging, we can safely treat the dataLayer as if it were an array as we’re in control and we’re not going to stomp on anyone else’s dataLayer operations.

Explore the dataLayer

In the console, inspect the dataLayer by executing the dataLayer command:

!168

Page 169: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Click the arrows next to each object to see the name-value pairs in each object literal:

Now we can start popping object literals off the dataLayer, manipulate them and then push them back to test our tags, triggers, and variables.

Lets change a value in this object literal to simulate a different click:

And see what happens when we push it back onto the dataLayer:

!169

Page 170: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

We just simulated a click on another element without making the click. Google Tag Manager was persuaded to behave as if we had just interacted with the page. When we performed this simulation, we got to see how it performed, what it did and hopefully understood why. Powerful stuff indeed. See that there is no need to always interact with the site - you can simulate events through dataLayer manipulation.

Moving beyond the inspection of the tracking pixel requests and looking deeper into the conversation between Google Analytics, Google Tag Manager and the browser is a very powerful technique. Ensure the advanced debugging features are used appropriately in preview mode and do not progress up stream towards the production environment.

The debug mode variable is a simple little switch that can be used to load Google Analytics in debug mode . 32

As can be seen from the verbose nature of the console output shown in the above example, the Google Analytics debug mode is a lot more revealing than the standard output. Pay attention to the warning in the GA documentation, using the

https://developers.google.com/analytics/devguides/collection/analyticsjs/32

advanced#debug

!170

These techniques are suitable for debugging. Manipulation of the dataLayer by scripts (other than pushing) is not recommended.

Use the debug mode variable to control the use of Google Analytics in debug mode

Page 171: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

debug mode in a production environment is not recommended for performance reasons.

Use the Debug Mode built in variable to automatically manage the GA debug mode usage.

Operational data capture

Assuming you’ve successfully built and deployed your GTM assets having fully tested them, you don’t expect any further issues or errors to debug, right? Wrong. Tracking operational issues such as JavaScript exceptions using Google Analytics via Google Tag Manager is simple and is a vital tool to ensure a quality user experience on your site.

Having enabled the Errors built in variables you’ll see object literals pushed onto the dataLayer when errors are detected after the container script has executed. Remember, until the GTM container has executed, any listeners won’t hear any thing.

Remember from the Reliable dataLayer Implementation chapter, if there is an error in the dataLayer, this error won’t be picked up by the Page Error Listener. The gtm.pageError object literal contains some very useful information:

- an event - gtm.pageError - The error line number

!171

Page 172: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

- The error message - The page or javascript file where the error occurred

This information is golden. This information can be passed to front end developers to demonstrate that errors happened, where and how to nail down the use case for the error. This is vital to reproduce the error which in turn is vital to be able to fix the error. Putting this data into Google Analytics is simple using an event tag. The built in variables to extract the data are straightforward to use and the trigger will use All JavaScript Errors as a trigger filter.

Choose to fire the error tracking event on all JavaScript error events initially. You may choose to fire specific tags to trap specific JavaScript errors or errors on specific pages at a later stage.

Of course, during the design phase, where the development team is involved in the process, you may jointly choose to define a structured approach to tracking discrete JavaScript exceptions. How this data is used may vary depending on the team responsible for the part of the site being tracked. The same thought process you employ when designing the user behaviour data structure can be applied to operational data - JavaScript exceptions and performance.

The Timing tag is a powerful tool that enables you to take full advantage of the Site Speed report suite in Google Analytics. The default set of reports are useful in general but you will have specific performance metrics that the site is expected to meet (and exceed). Using custom Timing tags as the ideal mechanism to use to fully enrich performance data.

!172

Page 173: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Insights extracted from the general Page Timings report will suggest general opportunities for optimisation. Include specific site functionality speed measurements in the operational data capture design process.

In summary, the combination of Google Tag Manager and Google Analytics affords the ability to capture user behaviour data and operational data. The power of these data sets in tandem to deliver a return on investment cannot be ignored.

!173

Page 174: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Documentation

Using a solid naming convention, version names and version notes will put you on an immediate strong footing regarding your system documentation. Systems are never fully self documenting but you can reduce the need for weighty tomes that are unlikely to be read and used by employing well written and readable code and comments. The code in the context of GTM refers to the naming and configuration of tags, triggers, and variables - not necessarily software code in the traditional sense. However, the correct approach is to design and build a system that is readable - write to be read. Build a system to be easily understood and maintained.

Use of existing conventions is a matter of common sense. Input from all stakeholders in a tag management solution project will contribute to the design and build of the system.

One of the key groups of stakeholders will be the development team. This team will use existing naming conventions in their coding standards. The conventions have a responsibility to convey the system vocabulary such that it is used in GTM too. Analysts, business owners and marketers will all have similar conventions. Understanding the scope of the tower of babel will enable a single tongue to be agreed and used such that the purpose of the tags, triggers, and variables will be clear to all stakeholders.

Beyond the naming of the GTM assets, the use cases for the tags, triggers, variables, and dataLayer variables will also require documentation. This documentation should exist already though.

!174

Page 175: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The specification deliverable from the design process will state clearly what assets are to be employed on each page, why and what the expected behaviour is. On a dynamic ecommerce site where there may be a large number of dynamic product and category pages groups of pages rather than individual pages can be referenced.

Use a tool similar to the spreadsheet shown below to document the requirements and the implementation. The spreadsheet is available to use for free at http://goo.gl/MjmD27

This is by no means a perfect or 100% complete solution but it is a working model that can be used to record and manage tags, triggers, variables, dataLayer requirements, dependencies and implementation details. If you’re a spreadsheet expert and can add magic to this asset, feel free to share your work with other GTM users.

!175

Page 176: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Chapter 14: Administration and configuration

Summary

Don’t be fooled by the ease of tag deployment through a tag management solution. Just because it’s easy, doesn’t mean that every man or woman and their dog (or cat) is invited to drop by and randomly scatter a few tags on the site.

The need for control and management of the assets is as essential as a general corporate security policy.

The zeal and rigour employed in the planning and design process also applies to operational considerations. The same potential for anti-pattern usage is present. As anti-patterns can be baked in from the start, they can also be introduced at any time during operation.

This section deals with three key areas of tag management operation:

- Controlling user access - Managing asset usage - Setup and management of containers

!176

Page 177: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Introduction

You have successfully avoided poor markup. You’ve been instrumental in including all relevant stakeholders through the entire planning, design, build, and testing phases of the project. Don’t sit back just yet though - going to production means this just got real.

By all means, deliver an outstanding solution now but avoid immediately opening the flood gates to all resources in the company. Just because the initial solution has been beautifully managed and solved does not mean the world stops and a zen-like calm descends. Change still happens.

Embrace change.

Manage and control change for the good of the solution.

The first port of call is managing and owning the ability to access the GTM front end. Look at who should have access to GTM and think why access is required.

Having granted appropriate access, what should users be allowed to do? Work closely with the development teams to manage the capabilities of GTM. Limit publication rights on the test and production containers. Maintain a good relationship with the engineers who build the site. It is likely that access and usage of a key resource like GTM will be managed by your IT team - perhaps you have a security team. This is correct and good.

Over time, the management task will scale with the usage of the tool. A series of useful heuristics is suggested that can reduce the management burden as the system grows. Your

!177

Page 178: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

GTM implementation can scale in terms of tag, trigger, and variable volume and usage. Complexity does not have to scale in a linear fashion with volume but correct ownership and control of access must sit with the correct authority.

!178

Page 179: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Managing users and user rights

Users can be granted access to specific GTM containers within an account with 4 levels of access on each container:

- View - Edit - Delete - Publish

Account level permissions allow read only or read/write access to the account.

Clearly, you will need to agree a process for granting access to Google Tag Manager as you would with any other mission critical resource. Apply common sense and sound judgement with respect to granting appropriate rights to individuals.

The production container will be the most precious resource and the most tightly controlled. The list of individuals who are permitted to publish the production container needs to be tightly controlled and supported with 2 phase authentication.

This serves two purposes:

- Tight control over who publishes the production container An extra step in the publication process allows for a reflective pause to confirm that you really do mean to publish the production container

- The access list needs to be a list of individuals. Whilst shared logins seem convenient, this is a fine example of a shortcut that will lead to bad things.

!179

Page 180: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

The quality of the data in the change history is degraded when a single account is used to quickly publish hacks and patches. Individual accountability is required to get valuable information from the publish history.

Avoid group accounts.

If individuals really have to get access to a GTM container to try a new tag or variable technique, remember, GTM is free so temporary containers can be set up for testing.

!180

Page 181: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Blacklisting and whitelisting assets

Remember back in the design and planning phases where all relevant stakeholders were included in the process?

There is a strong possibility that the security and engineering teams looked at the tag management solution through squinted eyes and personified scepticism in their reaction.

If they appeared doubtful and perhaps a touch negative or cautious, this is good. Such a reaction is healthy, to be expected and embraced. Their desire for control, accuracy and engineering discipline, all too often lacking in tag management, is well founded.

The planning and design process will have covered what measurements are required, when, why and how. The ‘how’ is very important. The ‘how’ dictates the type of tag to use.

Poor tag choice or poor tag design can lead to unpredictable and undesirable behaviour.

At the simplest and most common level, the custom HTML tag is the most common culprit for poor tag choice.

Abuse of the custom HTML tag manifests in a number of harmful ways:

- Poorly written JavaScript - Uncontrolled introduction of 3rd party (alien) JavaScript - Dependencies on 3rd party scripts and libraries

Having fought hard to reduce or eliminate 3rd party script dependencies, custom HTML tags can very easily include 3rd

!181

Page 182: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

party scripts in your container. Changes to 3rd party scripts are outside the control of the engineers who are responsible for the site. Their role now includes the need to parse, test and often debug custom HTML tags on a regular basis. This is an onerous overhead and needs to be avoided.

Engineering and security teams have the right and the ability to restrict tag execution by specific ID or by group. They can create white lists or black lists for tags and variables and therefore eliminate the need to manage rogue tags.

White and black listing of tags is discussed at length in the 33

Google Tag Manager documentation. The mechanics of listing the tag IDs or class IDs in the dataLayer to control tag execution are well documented. The fundamentally important message to communicate is the strict behaviour of the black and white lists. Engineers are required to understand the effects of specifying tag IDs or tag classes.

A further level of control is afforded to engineering staff regarding the approval of Floodlight tags. 3rd party marketing agencies can link DoubleClick to Google Tag Manager and can submit their Floodlight tags for approval by the engineers:

https://support.google.com/tagmanager/answer/3374209?hl=en-GB&ref_topic=3441532

In summary, engineering and security stakeholders do have a high degree of control over the behaviour of Google Tag Manager. With great powers come great responsibilities. The major decisions that are made prior to allowing or blocking tags via black and white listing will be made in the same arena

https://developers.google.com/tag-manager/devguide#security33

!182

Page 183: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

as the initial planning decisions - all stakeholders involved and contributing to ensure a cohesive and coherent solution is delivered.

Keep up with changes in GTM

In respect to the changes that are frequently deployed to Google Tag Manager, make sure all technical resources are familiar with and regularly check the Google Tag Manager Release Notes page:

https://support.google.com/tagmanager/answer/4620708?hl=en&ref_topic=6003219

!183

Page 184: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Accounts, Containers, Environments and Sites

Logging in to Google Tag Manager will show you the list of GTM accounts your login has access to. Normally, you will need only one GTM account per company. Quite correctly, an agency will create an account per client. Don’t create an agency account and run a container or set of containers per client. Consider that the account is the property of the client - not the agency. If the client changes agency, make it easy for the client to gracefully exit with all their assets under their control.

When you create a container, the text shown in the container name field contains the text: e.g. www.mysite.com.

This text suggests that the container holds the tags for a specific website. Think about that for a moment. Is this referring to a specific domain? Probably but with a subtle nuance that the domain may not be a public facing domain - you will most likely adopt a container per environment per site.

Splitting your containers like this allows you to maintain a production GTM environment whilst developing and testing new tags, triggers and variables without impacting on the public facing website.

At this point when creating a new container, make sure you have an empty version to publish in the event of a major issue. Use this blank version as a panic button. Have a safe version to publish in the high unlikely event that you need to disable all GTM functionality on your site.

!184

Page 185: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Ensure the blank container is published. Implementing the container script on a site without having at least one (hopefully empty) container published will result in a 404 error on all pages. The unpublished container does not exist and so, apart from in debug mode, the container asset cannot be delivered.

The perceived downside of the multiple container model is that there are three containers to manage and maintain - dev test and production. Users and their permissions need to be managed across multiple containers which can appear to be repetition of effort. Moving tags, triggers and, variables from one container to another is straightforward.

An alternative practice is to manage one container for all environments. There is only one container to manage, one container script, one set of users and permissions and no need to copy tags, triggers and variables between containers. This model uses carefully crafted triggers to fire tags on the correct environment.

This design may appear to offer a vast reduction in effort but this path is fraught with danger and further restriction. GTM development is normally an iterative process requiring multiple and frequent container publishes. Restricting publication rights will require a small set of users being requested to publish the container on behalf of other users. Repeatedly publishing a container being used on a production environment during development and testing is a high risk strategy.

Can you afford to rely on correct trigger usage to ensure the right tag fires on the right environment? Triggers will not work as intended often during development. Changes to variables can lead to unexpected changes in trigger behaviour.

!185

Page 186: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

This is a demonstration of the true cost of spending less time and thought on system design up front and favouring the quick win or path of least resistance.

The GTM interface describes how to set up containers. This is sound advice and worth following.

Splitting containers by function

A use case to carefully consider is the use of multiple containers to manage large scale implementations. A suitable use case is the organisation of functional verticals.

Functional verticals in terms of measurement refer to another level of the separation of concerns. Complex sites can quickly build up to a large number of assets. Managing assets, finding, modifying and understanding the relationships between assets can be time consuming. The functional verticals may well fall into the responsibilities of multiple different teams. These teams will find their jobs far easier to handle when they are only expected to manage their tags. Presenting a container that is specific to their concern is a sensible choice where high numbers of assets are present.

Here, we can choose to split containers by function:

- Navigation - Forms - Specific conversions - Video tracking - Member only functions - Non-member functions - Marketing

!186

Page 187: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

It is necessary that a shared core container will always be used on all sites. Simple page view tracking and GA configuration operations will be handled by this container.

At the point of deployment, the containers can be combined for use on a test environment using import/export functionality. Changes to the core container will be absorbed and unit tested on individual team containers to validate and approve the changes.

The advantage of using multiple containers is really felt on a complex site where changes to assets in one container can be safely hidden from other containers - a hard decoupling. Be even more aware of asset duplication in this case. As with the management of all large and complex sites, process is king. The ideal solution will combine elements of people, process and technology - don’t rely on the software alone.

Minimise changes between containers

The domain and UA ID lookup variables described in the Development and debugging section should be used to minimise the differences between development, testing, and production containers.

All possible measures to eliminate manual changes when moving assets between environment containers is strongly advised. The need for tag, trigger, or variable changes normally arises where development, staging, and production environments are different.

Poor maintenance of development and staging rigs post-release is usually the root cause of issues where patches are

!187

Page 188: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

applied to production in a rush after a release but are not also applied to dev and test environments.

This situation sounds horrendous and risky but it does happen. The dangers of shoddy engineering extend beyond quick fix hacks.

As with the planning process, the management and maintenance processes should also include all stakeholders and include input from all relevant areas of the business to ensure that operational changes are correctly assessed, planned and executed.

!188

Page 189: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Section 5 - Conclusion and next steps

What now?

!189

Page 190: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Conclusion…or is it?

Well done! You’re well on your way now. You’ve taken on a huge amount of advice and knowledge having got this far but success is never final.

That’s not to say you haven't or can’t deliver top quality GTM solutions right now. Of course you can but don’t sit back and think this is it.

Now you can start building your own bank vault of experience to continuously improve your GTM skills. Google Tag Manager isn’t sitting still which means you shouldn’t and can’t afford to. The product has been through huge changes whilst the Tag Management Solution industry has exploded.

This means the technical solution has changed significantly and will continue to evolve but the foundation of best practices will remain and will continue to reward you with successful projects.

Regardless of the functionality, the value of full stakeholder inclusion, planning, engineering rigour, precision, common sense, caring for the data your solution generates and, above all, doing things right will be most apparent and always tangible to the business.

Good luck!

!190

Page 191: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

Suggested further reading

Web Analytics 2.0, Avinash Kaushik: http://goo.gl/bS2yb2

Advanced Web Metrics with Google Analytics, Brian Clifton: http://goo.gl/RScMGl

Successful analytics, Brian Clifton: http://goo.gl/sOxfsw

Google Tag Manager Google+ Community: http://goo.gl/Ax4i4L

YouTube player tracking: http://goo.gl/2M6RKC

Vimeo video player tracking: http://www.sanderheilbron.nl/vimeo.ga.js/

Some of the very best GTM material on the internet: http://www.simoahava.com

GTM Form tracking: http://www.lunametrics.com/blog/2014/11/10/form-tracking-google-tag-manager

GTM Release notes. Check these regularly! https://support.google.com/tagmanager/answer/4620708?hl=en

!191

Page 192: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

About the author

Doug Hall is the Director of Analytics at ConversionWorks. Doug has 20 years industry experience working with global brands on Web Analytics and Conversion Rate Optimisation projects. A frequent conference speaker on CRO, Google Analytics and Tag Management, he has published a wide range of authoritative articles on the ConversionWorks and online-behaviour.com blogs (http://www.conversionworks.co.uk/blog/ , http://goo.gl/xk08KA).

Doug is a keen cyclist, amateur chef and beer brewer.

!192

Page 193: The Little Book of GTM Best Practices...Google Tag Manager (GTM) has mirrored the speed of evolution and growth of the Tag Management Solution (TMS) industry. Such an astonishing rate

About ConversionWorks

ConversionWorks is a web analytics and conversion rate optimisation agency that helps clients grow their online businesses. Formed in 2001, a Google Certified Partner, Certified Google Analytics Premium Reseller and Certified Google Analytics Partner, ConversionWorks has successfully delivered large scale Google Analytics and Google Tag Manager solutions and continues to grow.

!193