Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Google Tag Manager after opening body tag with javascript

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:

  • If I add this code to the head, it won't work because the body doesn't exist yet.
  • If I add this code to the body, it's already too late.

Is there something similar that can go into the head that initializes once the body tag is created?

like image 622
John R Perry Avatar asked Nov 09 '22 08:11

John R Perry


1 Answers

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.

like image 117
mediafreakch Avatar answered Nov 14 '22 21:11

mediafreakch