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?
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.
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.
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