Why use an async loader for third party JS

Viewed 103

The following general format is used by almost all third party hosted scripts for loading the resource.

<script type="text/javascript">
    (function(a,b,c,d){
    a='//third.com/party.js';
    b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true;
    a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a);
    })();
</script>

Why is that preferred to this:

<script type="text/javascript" src="//third.com/party.js" async></script>

My guess was that it extended async loading support to browsers that didn't have it, but almost all browsers used today support the async attribute.

1 Answers

Traditionally that type of obfuscated scripts is used to inject third party libraries into frameworks like Wordpress or other CMSes.

In Wordpress these script tags can then be processed, for example, by applying a filter with the script_loader_tag hook. An example here.

So, depending on how that script is handled you may endup with a case where the properties are stripped from the script. And then it's no longer async.

By enclosing your script in a function you're somewhat protecting it from tampering. Especially if you don't control how it is injected into the page. And also, that code can be extracted and concatenated or minified together with all the other page scripts.

Related