Skip to content

Instantly share code, notes, and snippets.

Created June 14, 2011 20:36
Star You must be signed in to star a gist
What would you like to do?
Optimised async loading of cross-domain scripts
* Updated to use the function-based method described in
* 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 && ( = id);
fjs.parentNode.insertBefore(js, fjs);
// Google Analytics
add(('https:' == location.protocol ? '//ssl' : '//www') + '', 'ga');
// Google+ button
// Facebook SDK
add('//', 'facebook-jssdk');
// Twitter SDK
add('//', 'twitter-wjs');
}(document, 'script'));
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.

Copy link

How can I add jQuery?

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