Last Updated: January 20, 2017
· idered

Better way to add Facebook, Twitter, Google Plus and any other external scripts

Every time I've to embed facebook, twitter or any other external script on website, it takes longer than it should and my code get messy. But no longer, with this code it's easier to embed scripts from external source.

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);

Although it's just a loop, it's really useful and helps to manage all those scripts.

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

Post from my blog

1 Response
Add your response

I'd add before the for loop:
var container = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

then replace that line inside the loop so you don't have to fetch the dom everytime.

over 1 year ago ·