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.
Written by Patrick Burtchaell
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#