I use GoogleTagManager script and dataLayer object. I read in documentation that dataLayer object has to be filled above the GTM script. But I need to add a product detail when the user chooses the product and it happens after the GTM script is loaded. If I use dataLayer.push(chosenObject) will this action call the Google Tag Manager script? Will it work?
Yes, you can push variables to the dataLayer at any time, the "trick" is in how to access the data from the dataLayer in your tags (plus if you declare you dataLayer above the GTM code you do not call "push" - you declare it as a variable so you can push later).
It's necessary to declare the data in the dataLayer if you want to use it as soon as the page loads - the standard pageview trigger will run as soon as the GTM code has loaded (i.e. before the page has finished loading), so obviously GTM can only access data that preceeded it in the code.
Triggering tags in GTM takes an event (do not confuse with Google Analytics events or Javascript events, event in GTM is just a reserved variable name).
A few events are produced by GTM implicitly - the pageload-event, DOM ready, click and submit events.
If at some later point you want to trigger an element to respond to a value you pushed to the dataLayer you need a custom event:
dataLayer.push({
'event':'i_pushed_a_value',
'payload' : 'this is my data'
})
(please not that data comes in key->value pairs).
Now you can have a trigger that fires on the event i_pushed_a_value
, and you can use a custom variable of the type dataLayer (enter the key, in this case payload
, as key in the variable configuration) that holds your data.