David Hirst
David Hirst

Reputation: 2002

Why do developers write these type of scripts for embedding when a simple tag would do?

I just wanted to ask a question about a practice I have seen quite a lot recently regarding jQuery/Javascript plugins/widgets written by other developers.

I maintain a number of sites and I am usually asked to add new scripts for various things such as chat widgets, marketing tools etc etc however the code I am usually sent for the majority of these looks is something like this.

<script type="text/javascript">

(function() {

var hm = document.createElement('script'); hm.type ='text/javascript';     hm.async = true;

hm.src = ('++www-widget-org+widget-js').replace(/[+]/g,'/').replace(/-/g,'.');

var s = document.getElementsByTagName('script')[0];     s.parentNode.insertBefore(hm, s);

})();

</script>

Now my question is why go to all the trouble of writing the above script when all you really need to do is this?

<script src="//www.widget.org/widget.js" type="text/javascript" async></script>

I have seen this a number of times and I am beginning to wonder what the benefit of this approach actually is? If there is one?

Upvotes: 4

Views: 120

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

According to Steve Souders, this method is used to load scripts in a non-blocking fashion. This makes sense given these scripts are generally supplemental to the page and not directly related to function (why make your site slow just because you added Google Analytics, etc.).

There's other scripts that use this opportunity to initialize some very basic data (e.g. GoogleAnalytics uses this to _setAccount). I've also seen scripts aggregate user statistics (screen size, agent, and other client data) and pass them off to the remote script as well (in query parameters they can later review/analyze to gain detail about their demographic).

Upvotes: 2

Related Questions