Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Tag Manager script injection

I have recently been tasked with cleanup of our GTM tags. I notice that a lot of the tags include remote scripts by injecting them into the DOM using JS, for example:

var head = document.getElementsByTagName('head')[0]
var js = document.createElement('script');
js.src = 'https://cdn.somewhere.com/script.js';
head.appendChild(js);

Is there a specific reason why people do it this way instead of just using this?

<script type="text/javascript" src="https://cdn.somewhere.com/script.js" async></script>

What are the benefits of doing it the first way? Is there a better way to handle external scripts?

like image 607
Marcus Horne Avatar asked Apr 07 '20 16:04

Marcus Horne


2 Answers

I found only one reason to do so but not sure if that is still actual nowadays. As said in this article GTM strips some script attributes and if it's required to have them it's better to add the script programmatically.

like image 76
Oleksandr Kovpashko Avatar answered Oct 17 '22 11:10

Oleksandr Kovpashko


With GTM, there isn't really a point. The idea behind append script elements to the head is to affect load order, but since you first need to load GTM, which then injects the create element/append code into an arbitrary position before it runs, with GTM this otherwise sensible approach just creates an unnecessary extra step.

It's moot in any case, because these days you would neither use create/append, nor script tags in a Custom HTML tag. The way to go now is to create a custom template and use the injectScript API.

like image 34
Eike Pierstorff Avatar answered Oct 17 '22 13:10

Eike Pierstorff