This week, I needed to solve a problem with Google Tag Manager (GTM).
The problem was that my platform has different themes for each client, and I needed to insert the GTM code for each theme.
The problem:
Google Tag Manager (GTM) was not working correctly because its ID was being dynamically loaded on the client side. However, GTM needs to be available immediately when the page loads. This caused issues such as:
- GTM not initializing at the right time.
- Important tracking events (like pageviews) being lost.
For example
// This will not work
function Example(gtmId){
return <GoogleTagManager gtmId={gtmId} />
}
Solutions Attempted
- Loading GTM as a Dynamic Component: GTM was loaded as a dynamic component after the page rendered, which delayed execution and prevented it from working correctly.
- Loading GTM Dynamically on the Client Side: GTM was also loaded only on the client side, but since it needs to be available at the initial page load, this approach failed.
The solution
To ensure GTM loads during the initial page render, we use the following approach:
- Define Preconfigured GTM Instances
const GoogleTagManagerInstancies: { [key: string]: () => JSX.Element } = {
cobrand1: () => <GoogleTagManager gtmId="GTM-XXXXXX" />,
cobrand2: () => <GoogleTagManager gtmId="GTM-YYYYYY" />,
default: () => <></>,
};
- Select GTM Based on Theme
const WaGoogleTagManager = GoogleTagManagerInstancies[activeTheme ?? "default"];
- Render the Component
<WaGoogleTagManager />
Why Does This Work?
- GTM is statically defined at the initial page load.
- The GTM ID is resolved before rendering, ensuring the script loads at the right time.
Conclusion
The issue was caused by GTM being loaded too late, preventing it from executing correctly. The solution ensures that GTM is loaded before rendering, using preconfigured instances and direct rendering in the HTML.
Top comments (0)