Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consequences of including an external script file in a GTM tag

In GTM, lets say that I have a "custom HTML" tag, and in it include an external script file like

<script type="text/javascript" src="http://externalsite.com/file.js"></script>

How is this file loaded? Does it affect the loading time of the page?

I know that the GTM script is loaded asynchronously along with the tags, but I can't really imagine what happens in this case.

like image 939
joakimdahlstrom Avatar asked Sep 20 '13 11:09

joakimdahlstrom


People also ask

Can external scripts contain script tags?

External scripts cannot contain <script> tags.

Does GTM affect performance?

Does Google Tag Manager slow down the site? The most absolute answer is yes. Just like any additional line of code added to the site, it will have some impact on the page loading speed.

Where do GTM scripts go?

Install the tag on every page of your website using the instructions provided. The first code block is best placed immediately after the web page's opening <head> tag, or as high in the <head> as possible. This helps to ensure that your Tag Manager configuration is available and ready when the rest of the page loads.


2 Answers

In you GTM custom HTML tag, you can even use the async or defer attributes:

<script async type="text/javascript" src="/path/to/file.js"></script>

Further reading: http://davidwalsh.name/html5-async

And if you are using HTML5, type defaults to text/javascript, so you can leave it off.

Alternatively you could load asynchronously using an anonymous self invoking function:

<script>
(function(d,s){
var e = d.createElement(s),
m = d.getElementsByTagName(s)[0];
e.async = 1;
e.src = '//externalsite.com/file.js';
m.parentNode.insertBefore(e,m);
})(document,'script');
</script>
like image 100
Mike Causer Avatar answered Sep 19 '22 14:09

Mike Causer


How is this file loaded?

Asyncronously, keeping script order.
Despite you writing it as an html <script> tag, GTM loads it creating a DOM script element instead.
This is roughly the code used (not taken from GTM directly as minified):

var script = document.createElement('script');
script.src = '/path/to/file.js';
script.async = false;

Does it affect the loading time of the page?

Yes. While the way GTM loads scripts impacts page loading speed as little as possible, scripts still have a significant impact.
There are ways to mitigate the impact, although third parties are generally harder to optimise.

like image 32
Razor Avatar answered Sep 23 '22 14:09

Razor