Why do custom javascript variables in Google Tag Manager run multiple times

I'm trying to understand why the custom javascript in Google Tag Manager is firing unexpectedly often. Ultimately, the tag is only firing once, as expected, so it's not problematic, I'm just looking to understand it and if there is a more efficient way I can do it.

I started with a blank container on Google Tag Manager.

I created 3 simple custom javascript variables:

Test - Category

function()
{
  console.log(JSON.parse(JSON.stringify(window.dataLayer)));
  console.log("Category fired");
  return "Category";
}

Test - Action

function()
{
  console.log(JSON.parse(JSON.stringify(window.dataLayer)));
  console.log("Action fired");
  return "Action";
}

Test - label

function()
{
  console.log(JSON.parse(JSON.stringify(window.dataLayer)));
  console.log("Label fired");
  return "Label";
}

I created a GA event tag in GTM:

  • Tag type: Google Analytics: Universal Analytics
  • Track type: Event
  • Category: {{Test - Category}}
  • Action: {{Test - Action}}
  • Label: {{Test - Label}}

And the trigger is 'all clicks'.

I put Tag Manager into preview mode and tested.

As soon as the page has loaded, before I've made any clicks, the console logs:

[{}] Array (length: 1)

Category fired

Action fired

[{}] Array (length: 1)

Category fired

Action fired

Label fired

[{}] Array (length: 2)

Category fired

Action fired

[{}] Array (length: 2)

Category fired

Action fired

Label fired

[{}] Array (length: 3)

Category fired

Action fired

[{}] Array (length: 3)

Category fired

Action fired

Label fired

When I make one single click, console log:

[{}] Array (length: 4)

Category fired

Action fired

[{}] Array (length: 4)

Category fired

Action fired

[{}] Array (length: 4)

Category fired

Action fired

Label fired

On page load, the first 2 variables (category and action) are firing twice for every push to the data layer, while the 3rd (label) just fires once.

On click (a single push to the data layer), the first 2 variables (category and action) fired 3 times, and the third (label) fired just once.

Can anyone explain why the first 2 variables are being evaluated multiple times for each push to the data layer?

Answers

When you're in Preview/Debug mode, every variable gets evaluated with every event that is pushed into the data layer.

Posted on by Robert Miller