Last Updated: February 25, 2016
·
1.619K
· pb

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

var scripts = {
   'facebook-jssdk': '//connect.facebook.net/en_US/all.js#xfbml=1',
   'googleplus'    : 'https://apis.google.com/js/plusone.js',
   'twitter-wjs'   : '//platform.twitter.com/widgets.js',
   'analytics'     : ('https:'==location.protocol?'//ssl':'//www') + '.google-analytics.com/ga.js'
 }, script, _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];

 for (var id in scripts) {
   script = document.createElement('script'); script.src = scripts[id];
   script.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 ·