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.
Actually your code inserts script
between the head
and body
tags. Use this instead:
var s = document.body.firstChild;
s.parentNode.insertBefore(gtm, s);
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
.
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