Google Tag Manager Fires Too Early?
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.
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.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?