Ad

Google Tag Manager Fires Too Early?

- 1 answer

I am using the react-gtm-module to write a datalayer produced dynamically in react to a custom HTML tag. I have an issue where sometimes the CustomHTML tag is fired successfully, and the dataLayer is produced, but the <script type='application/ld+json'> element is missing the templated dataLayer variables.

It occurs both in the dev and production environments, so it cannot be webpack related. Sometimes the gtm debugger shows the tag with the empty fields in the failing case and sometimes it shows the fields populated in the tag even though the written element itself does not.

Here is the writing script in the CustomHTML tag:

var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.innerHTML = JSON.stringify(data);
  document.getElementsByTagName('head')[0].appendChild(script);
})(document); 

Here are two examples which are essentially equivalent:

https://iiif.cloud/view/afa9ee3c-a7ed-5875-a009-2de3940ebff3

the tag is written into the application/ld+json element.

and here:

https://iiif.cloud/view/7145e94f-6a10-5bb6-a360-6915ee9b0795

where it is not. Any suggestions for debugging this further would be appreciated.

Ad

Answer

The problem is that the trigger needs to wait for the dataLayer to be populated. There is a trigger option to delay execution, "Set minimum on-screen duration". By setting this to 2000ms, the tag is now always created with the dataLayer variables.

Ad
source: stackoverflow.com
Ad