Created
November 24, 2011 02:25
-
-
Save localpcguy/1390496 to your computer and use it in GitHub Desktop.
Async Third party script loader after body.onload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
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
Works fine, but "scriptLoadedCallback" function isn't defined and callbacks don't work.