Skip to content

Instantly share code, notes, and snippets.

@necolas
Created June 14, 2011 20:36
Embed
What would you like to do?
Optimised async loading of cross-domain scripts
/*
* Updated to use the function-based method described in http://www.phpied.com/social-button-bffs/
* Better handling of scripts without supplied ids.
*
* N.B. Be sure to include Google Analytics's _gaq and Facebook's fbAsyncInit prior to this function.
*/
(function(doc, script) {
var js,
fjs = doc.getElementsByTagName(script)[0],
add = function(url, id) {
if (doc.getElementById(id)) {return;}
js = doc.createElement(script);
js.src = url;
id && (js.id = id);
fjs.parentNode.insertBefore(js, fjs);
};
// Google Analytics
add(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
// Google+ button
add('https://apis.google.com/js/plusone.js');
// Facebook SDK
add('//connect.facebook.net/en_US/all.js', 'facebook-jssdk');
// Twitter SDK
add('//platform.twitter.com/widgets.js', 'twitter-wjs');
}(document, 'script'));
@ngryman
Copy link

ngryman commented Mar 28, 2013

Here is an updated version including the updates of @mathiasbynens from his post on the similar topic + some adjustments.

JSFiddle: http://jsfiddle.net/ngryman/cEuxD/
Fork: https://gist.github.com/ngryman/5266324

  • using all relative urls: google plus seems to work wo/ https, and gga now works w/ relative urls.
  • not using document fragment as I find it a little bit overkill :)
  • using the iframe version of the Facebook button (not in the docs anymore I think, but works).
(function(d, u) {
    var s = d.scripts[0],
        i = u.length, g;
    while (i--) {
        g = d.createElement('script');
        g.src = '//' + u[i] + '.js';
        s.parentNode.insertBefore(g, s);
    }
}(document, [
    // Google Analytics
    'google-analytics.com/ga',
    // Google+ button
    'apis.google.com/js/plusone',
    // Facebook SDK
    'connect.facebook.net/en_US/all',
    // Twitter SDK
    'platform.twitter.com/widgets'
]));

@tomasdanilevicius
Copy link

@zenopopovici - to set api_key, LinkedIn needs a callback. I forked this GIST a while ago and added callback method, you can preview it here: @3952471 . I know it's outdated, but I hope you'll be able to figure it out.

@anselm-urban
Copy link

How can I add jQuery?

@maartentibau
Copy link

I would change the while statement to this

while (i--) {
    var  src = (u[i].lastIndexOf('http', u[i]) === -1) ? '//' + u[i] : u[i];

    g = d.createElement('script');
    g.src += (u[i].indexOf('.js', u[i].length - 3) === -1) ? src + '.js' : src;
    s.parentNode.insertBefore(g, s);
}

This makes the following things possible:

  • it's possible to add scripts with ".js" at the end
  • it's possible to add files with an absolute URL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment