I know that I can prepend some html to a page by using insertAdjacentHTML and the afterbegin position like this:
var x = document.getElementsByTagName("body")[0];
x.insertAdjacentHTML('afterbegin','<!-- GTM code goes here -->');
Here's the problem:
head, it won't work because the body doesn't exist yet.body, it's already too late.Is there something similar that can go into the head that initializes once the body tag is created?
You could put this into the <head> section:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var script = document.createElement("script");
script.innerHTML = "[GTM JS goes here]";
document.body.insertBefore(script, document.body.firstChild);
});
</script>
Make sure you only place the part from within <script> from the GTM code into the illustrated placeholder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With