Created
January 23, 2023 10:26
-
-
Save geekhunger/0377145c0e709ba2229f582f550fcda0 to your computer and use it in GitHub Desktop.
Easy GTM Script Include
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
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) | |
}) | |
} |
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
<!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