Last Updated: February 25, 2016
· pb

A better way to add Social Media scripts and any other external scripts

var scripts = {
   'facebook-jssdk': '//',
   'googleplus'    : '',
   'twitter-wjs'   : '//',
   'analytics'     : ('https:'==location.protocol?'//ssl':'//www') + ''
 }, script, _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];

 for (var id in scripts) {
   script = document.createElement('script'); script.src = scripts[id]; = id;script.type = 'text/javascript'; script.async = true;
   (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);

Don't forget to add <div id="fb-root"></div> to your markup when you're using Facebook.

2 Responses
Add your response

Forgive my ignorance, but why is this a better way? Performance improvement or merely "neater" coding?

over 1 year ago ·

There isn't much of a performance improvement; I write my scripts this way simply to keep them organized.

However, you could easily turn this method into one that improves by deferring the download of the scripts until after page load. Add a bit of code that loads the scripts listed in the loop ONLY after the page has loaded.

over 1 year ago ·