Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place a script immediately after the opening <body> tag

I would like to place a Google tag manager script and according to Google Tag documentation, the script should be placed immediately after the opening tag.

Since we cannot change the source code, we have to append the script using the following code snippet.

<script type="text/javascript">
(function () {
    var url = "path/to/js/file";
    var gtm = document.createElement('script');
    gtm.type = 'text/javascript';
    gtm.async = true;
    gtm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + url;
    var s = document.getElementsByTagName('body')[0];
    s.parentNode.insertBefore(gtm, s);
})();
</script>

It is almost the same as Google analytics script snippet. Now the script is appended right before the body tag. I am not sure if using jQuery method insertAfter is the proper way to do it or if there is a better way!

I appreciate your kind help.

like image 574
digitup Avatar asked Feb 08 '13 09:02

digitup


2 Answers

Actually your code inserts script between the head and body tags. Use this instead:

var s = document.body.firstChild;
s.parentNode.insertBefore(gtm, s);
like image 161
Teemu Avatar answered Oct 05 '22 23:10

Teemu


You can use Node.insertBefore for this:

var body = document.getElementsByTagName("body")[0];
body.insertBefore(gtm, body.firstChild);

This works even if body tag has no firstChild.

like image 29
Salman A Avatar answered Oct 06 '22 00:10

Salman A