Insert Google Tag Manager after opening tag tag using javascript

I know that I can add some html to the page using the insertAdjacentHTML and 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 head , it will not work because the body does not exist yet.
  • If I add this code to body , it's already too late.

Is there something like this that can enter the head, which is initialized after the creation of the body tag?

+5
source share
1 answer

You can put this in 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 the <script> from the GTM code in the illustrated placeholder.

+1
source

Source: https://habr.com/ru/post/1257492/


All Articles