Skip to content

Instantly share code, notes, and snippets.

@localpcguy
Created November 24, 2011 02:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localpcguy/1390496 to your computer and use it in GitHub Desktop.
Save localpcguy/1390496 to your computer and use it in GitHub Desktop.
Async Third party script loader after body.onload
<script>
// Credit to:
// Original function adapted from Facebook async script at - http://www.phpied.com/social-button-bffs/
// http://twitter.com/aaronpeters
// http://www.aaronpeters.nl/blog/why-loading-third-party-scripts-async-is-not-good-enough
(function(w, d, s) {
function go(){
var js, fjs = d.getElementsByTagName(s)[0], load = function(url, id, cb) {
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.src = url; js.id = id;
fjs.parentNode.insertBefore(js, fjs);
// if callback, execute the callback.
if (typeof cb === 'function') {
js.onload = cb.call(this, id);
// For IE
js.onreadystatechange = function (id) {
if (this.readyState === 'complete' || this.readyState === 'loaded') {
cb.call(this, id);
}
};
}
};
load('//connect.facebook.net/en_US/all.js', 'fbjssdk', false);
// Uncomment the following for Google or Twitter
//load('https://apis.google.com/js/plusone.js', 'gplus1js', false);
//load('//platform.twitter.com/widgets.js', 'tweetjs', false);
}
if (w.addEventListener) { w.addEventListener("load", go); }
else if (w.attachEvent) { w.attachEvent("onload",go); }
}(window, document, 'script'));
</script>
@NoodlesNZ
Copy link

Works fine, but "scriptLoadedCallback" function isn't defined and callbacks don't work.

@localpcguy
Copy link
Author

You have to define the callback function separately, see the comment a couple lines up: The function needs to be created seperately or it will error.

I should update this though, rather than pass true/false for the cb var, and call a function called scriptLoadedCallback, I just pass the callback itself.

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