Skip to content

Instantly share code, notes, and snippets.

@tomasdanilevicius
Forked from necolas/snippet.js
Created October 25, 2012 13:13
Show Gist options
  • Save tomasdanilevicius/3952471 to your computer and use it in GitHub Desktop.
Save tomasdanilevicius/3952471 to your computer and use it in GitHub Desktop.
Optimised async loading of cross-domain scripts with callback
/*
* Added callback
*
* 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],
getScript = function(url, id, callback) {
if(doc.getElementById(id)) {return;} js = doc.createElement(script);
js.src = url; id && (js.id = id); fjs.parentNode.insertBefore(js, fjs);
js.onload = js.onreadystatechange = function() {
if(!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
if(callback) { callback(); }
}
};
};
getScript(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
getScript('//connect.facebook.net/en_US/all.js#xfbml=1', 'facebook-jssdk');
getScript('//platform.twitter.com/widgets.js', 'twitter-wjs');
getScript('//platform.linkedin.com/in.js?async=true', 'linkined-jsapi', function() { IN.init({ api_key: 'YOUR_API_KEY' }); });
}(document, 'script'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment