dataLayer.push not working after GTM script

后端 未结 1 828
后悔当初
后悔当初 2021-02-08 21:40

I want to implement the Enhanced Ecommerce with Google Tag Manager and I want to push some data for the tag Universal Analytics.

I always created the dataLayer before t

相关标签:
1条回答
  • 2021-02-08 22:28

    You're not following best practices, so you'll run into issues, sooner or later.

    • Always use .push instead of initialization: your first call is an array initialization (dataLayer = [). This means that if the dataLayer already exists, it will be completely overwritten, including the .push method which is customized by GTM in order to receive pushed events. Right now it's working fine because you're calling GTM after the initialization. But it's a bad habit to take. One day you will move GTM above that initialization or add similar initialization calls after GTM, and it will break.

    Your calls should be:

    window.dataLayer = window.dataLayer || [];  
    dataLayer.push({...});
    
    • Always set the event property: the event property is what is used by GTM to define triggers and know when data becomes available. You can have 2 successive .push calls, the 1st with an event, and the 2nd without, and the data from the 1st will be available in the 2nd event (as long as that event doesn't overwrite it), but once again that's bad habit and playing with fire.

    For instance:

    dataLayer.push({
      'event': 'ecommerce', // naming is up to you, should match your GTM triggers 
      'ecommerce': {
      ...
    

    In your particular case, since the event key is missing, it works as long as GTM loads after the push, because the data is already there when GTM kicks in. When the push call is moved after GTM, because there is no event property, there is just no way for GTM to know when data becomes available. So you should:

    • Add the event key (always!)
    • Configure a trigger which matches the event

    Here is some more reading on those topics:

    • https://www.simoahava.com/gtm-tips/datalayer-declaration-vs-push/
    • https://www.simoahava.com/gtm-tips/add-the-event-key-to-datalayer-pushes/
    0 讨论(0)
提交回复
热议问题