Fix Undefined DataLayer Variables in Google Tag Manager After Updating Drupal Datalayer Module to 2.1.x
When we updated our Drupal sites to Drupal 11 and also upgraded the DataLayer module to its latest version (2.1.0), we encountered an issue where all DataLayer variables passed to Google Analytics via Google Tag Manager were showing as undefined or not set. Further debugging revealed that this issue arises because the initialization of the DataLayer variables has been moved to the footer of the page and now uses a lazy build approach. Consequently, tags that trigger on the Pageview event in GTM might not have access to these variables, leading to incomplete or missing data in your analytics.
Undefined DataLayer Variables on Pageview
The change in the DataLayer module version 2.1.0 involves shifting the script that initializes the DataLayer variables from the page header to the footer. Additionally, the script is now loaded using a lazy build approach, meaning it is only rendered when needed, further delaying its availability. This change can cause issues for GTM tags that rely on DataLayer variables during the Pageview event since these variables may not yet be initialized when the tags fire.
The Solution: Use DOM Ready Instead of Pageview Trigger
To address this issue, you should modify your GTM setup to trigger tags on the DOM Ready event instead of the Pageview event. The DOM Ready event fires after the HTML document has been fully loaded and parsed, ensuring that the DataLayer script (now in the footer) has executed and all variables are available.
Here’s how you can implement this solution:
Adjust Your GTM Trigger:
- In your GTM workspace, locate the tag that needs access to DataLayer variables.
- Change its trigger from Pageview to DOM Ready.
- Save and publish your changes.
Handling GA4 Configuration Tags:
- If you were passing DataLayer variables as parameters in a Google Tag (such as a GA4 configuration tag) that triggers on Pageview and you want to keep it that way, you can create a new GA4 event tag instead.
- Configure this new tag to trigger on DOM Ready.
- Within this event tag, you can safely reference the DataLayer variables, ensuring they are sent to GA4 as custom dimensions or matrices.
Conclusion
By triggering your GTM tags on Dom Ready rather than Pageview, you can effectively mitigate the issues caused by the DataLayer initialization moving to the footer in Drupal's DataLayer module version 2.1.x. This approach ensures that all DataLayer variables are available when needed, allowing your analytics setup to continue functioning smoothly.