Sameer
Sameer

Reputation: 71

Place datalayer.push code in google tag manager

Being new to GTM. My question might be very lame. I have following query in regards to datalayer.push code/method/function If i want to place datalayer.push code/method/function on web pages were should i place the code on the page 1) should it be above GTM code 2) should it be below the GTM code 3) should I place it were I declare/define the datalayer

Also, would like to know if there are rules that need to be followed while placing the datalayer.push code/method/function on the pages Thanks in advance.

Upvotes: 0

Views: 1583

Answers (1)

nyuen
nyuen

Reputation: 8907

Some best practices regarding the dataLayer including defining the initial dataLayer BEFORE the GTM container:

<body>
   <script>
      dataLayer = [{
         'event': 'someEvent',
         // other parameters
      }]
   </script>

   <!-- Google Tag Manager -->
   ...
   <!-- End Google Tag Manager -->

and if you want to do a dataLayer.push, then that also should come before the container.

<body>
   <script>
      dataLayer = [{
         'event': 'someEvent',
         // other parameters
      }]
   </script>

   <script>
      dataLayer.push({
         'category': 'clothing',
         // other additional parameters
      })
   </script>

   <!-- Google Tag Manager -->
   ...
   <!-- End Google Tag Manager -->

In some cases, you may want to check to see if the data layer object has been defined or not first, before pushing to it:

window['dataLayer'] = window['dataLayer'] || []
dataLayer.push({
   'newVar': 'newValue'
})

Upvotes: 2

Related Questions