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);

Here are two examples which are essentially equivalent:

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

and here:

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



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.