How To Load Multiple Google Tag Manager Container IDs Properly
As much as Google touts page speed as a critical performance metric when determining the user experience and its impact as a ranking factor, it is quite ironic since their properties are ridiculously slow.
Typical Google Tag Manager Script
The typical implementation of Google Tag Manager requires you to load two scripts, one in the head and one at the end of the body. Example:
High in the <head> tag:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->
After the <body> tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
However, some companies need to load more than one GTM container and make the mistake of just adding the additional script tags. This method works but requires additional HTTP requests, impacting the site’s overall performance. The proper method is to load a single script and then pass multiple container IDs within them.
Multiple Container Google Tag Manager Script
You will have to forego the standard copy-and-paste code provided by Google Tag Manager when passing multiple Container IDs. In the following code sample, I’m loading two different container IDs from Google Tag Manager:
High in the <head> tag:
<!-- Google Tag Manager -->
<script>
dataLayer = {
'gtm.start': {
'GTM-XXXXXXX': true,
'GTM-YYYYYYY': true
}
};
</script>
<!-- Google Tag Manager script -->
<script src="https://www.googletagmanager.com/gtag/js"></script>
<script>
gtag('js', {
'gtm.start': dataLayer['gtm.start']
});
</script>
<!-- End Google Tag Manager -->
After the <body> tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX,GTM-YYYYYYY"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
If you have more than two container IDs, add their Container IDs in the dataLayer array in your head tag and append it comma-delimited to the iframe path in the body.
Keep in mind that this doesn’t save a lot of time. As the script is executed, it must still trigger each of your Google Tag Manager accounts’ tags. However, it does save you the round trip when executing each script and making each request for the initial script.