Skip to content

Instantly share code, notes, and snippets.

@geekhunger
Created January 23, 2023 10:26
Show Gist options
  • Save geekhunger/0377145c0e709ba2229f582f550fcda0 to your computer and use it in GitHub Desktop.
Save geekhunger/0377145c0e709ba2229f582f550fcda0 to your computer and use it in GitHub Desktop.
Easy GTM Script Include
const attr = "data-gtm"
const gtm = document.head.querySelector(`script[${attr}]`) // basically reference to itself
if(gtm) {
window["dataLayer"] = window["dataLayer"] || []
window["dataLayer"].push({
"event": "gtm.js",
"gtm.start": new Date().getTime()
})
const tag = gtm.getAttribute(attr)
const identity = `?id=${tag}&l=dataLayer`
let script = document.createElement("script")
script.async = true
script.src = "https://www.googletagmanager.com/gtm.js" + identity
document.addEventListener("DOMContentLoaded", function() {
const leader = document.querySelector(`script:not([${attr}])`) // first included script in the document
const tooltip = document.createElement("noscript")
const messenger = document.createElement("iframe")
messenger.src = "https://www.googletagmanager.com/ns.html" + identity
document.head.insertBefore(script, leader)
tooltip.append(messenger)
document.body.prepend(tooltip)
})
}
<!doctype html>
<html>
<head>
<title>Easy GTM Include</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="application/javascript" src="./gtm.js" data-gtm="GTM-XXXXXXX"></script>
</head>
<body>
<p>See the <code>script</code> tag above, with its <code>data-gtm</code> attribute? (Paste your Google Tag Manager E-Tag there.)</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment