Last active
November 5, 2023 20:19
-
-
Save szepeviktor/62c1f1aa80f14f985febd79e881cd693 to your computer and use it in GitHub Desktop.
Google Tag Manager loader for Vite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Google Tag Manager loader | |
* | |
* VITE_GTM_ID="GTM-XXXXX" | |
* VITE_GTM_DL_NAME=dataLayer | |
* | |
* @see https://developers.google.com/tag-platform/tag-manager/web/datalayer | |
*/ | |
// Skip adding <noscript> element | |
(function (win, doc) { | |
var containerId = import.meta.env.VITE_GTM_ID; | |
var dataLayerName = import.meta.env.VITE_GTM_DL_NAME; | |
var gtmScript = doc.createElement("script"); | |
var gtmScriptUrl = new URL("https://www.googletagmanager.com/gtm.js"); | |
if (typeof containerId !== "string" || typeof dataLayerName !== "string") { | |
return; | |
} | |
if (!Array.isArray(win[dataLayerName])) { | |
win[dataLayerName] = []; | |
} | |
// Add 2 new items to data layer | |
win[dataLayerName].push({ | |
"gtm.start": Date.now(), | |
"event": "gtm.js" | |
}); | |
gtmScriptUrl.searchParams.append("id", containerId); | |
if (dataLayerName !== "dataLayer") { | |
gtmScriptUrl.searchParams.append("l", dataLayerName); | |
} | |
gtmScript.async = true; | |
gtmScript.src = gtmScriptUrl.toString(); | |
doc.head.appendChild(gtmScript); | |
}(window, document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment