Google Tag Manager script injection

Viewed 8264

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?

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

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.

With the second code you write it in the document in not specific position (or defined by GTM), instead with appendChild appends the element to the specified element (in this case head).

Another use case for this approach is when someone hasn't got access to source code but they want to run scripts. It's kind of hacking because site owner might not even know the scripts are there. Could be legitimate use as well, i.e. a 3rd party hosted website where the site manager hasn't got permission to source code.

The reason you may do this is to speed up website loading.

By loading scripts after page load, you can significantly increase your PageSpeed Insights score.

Here is an example where the developer used Google Tag Manager to load livechatinc.js (a notoriously slow script) after page load:

Load livechatinc code after webpage is fully loaded

Unfortunately, using Google Tag Manager adds ~300ms to your page load speed over Universal Analytics. But generally, this 300ms is far smaller than a script like Live Chat Inc's which can add 1-2 seconds.

Related