Search code examples
google-tag-managerenhanced-ecommerce

can the dataLayer be defined above the gtm script and then data be pushed to dataLayer below the gtm script?


in google documentation for dataLayer it says

If you put the Google Tag Manager container snippet above the dataLayer array, Google Tag Manager may malfunction, and will not be able to read the variables defined in the array.

my question is: is it possible to declare the variable(dataLayer) above the GTM container and then push events to it (dataLayer) below the GTM?


Solution

  • Yes. That's not only possible, that's what GTM itself does (if you have a dataLayer variable declared, GTM pushes its gtm.js, gtm.dom and gtm.load event to the existing dataLayer (if this is undefined it declares the variable itself).

    One thing you need to remember is that you need to push a GTM event - literally, a key/value pair where the key is "event". The GTM code amends the native push-Method of the datalayer to scan for the "event" keyword, and if the keyword is found it updates its internal variables (i.e. you cannot access the new variables before a GTM event has been pushed).

    E.g. if you wanted to have a dataLayer variable "foo" with the value of "bar" you'd need to do

    dataLayer.push({
    "foo":"bar",
    "event":"myCustomEvent"
    });
    

    You can then access the foo variable and retrieve its value. You can also do a custom event type trigger, that fires as soon as the event "myCustomEvent" is pushed (you do not have to, though, the "bar" value will be retained until the page is unloaded, you push another value to the "foo" key or you reset the dataLayer).

    Some triggers types like click, submit and visibility provide their own events.

    The other thing to keep in mind is that you must not declare the dataLayer variable a second time after the GTM code has loaded, else you remove the changes GTM has made to the dataLayer and GTM breaks.

    But in short, yes, that's totally who it is supposed to work, you can push values after the GTM code.