Zocoi Vietnamese /ʒoʊ kɔɪ/: (informal) Let's watch/read together

Include one JavaScript file from another without the magic of jQuery

Today one of the challenges was to dynamically load JavaScript files from a piece of JavaScript. The job could have been easily done with the help of jQuery.getScript function. However, I was not allowed to use jQuery since the script was required to be library independent, that's why I came up with a function that mimics jQuery.getScript

In the example below, I was trying to get Facebook Connect js library and call a init function after it has been loaded. So far it has served me well.

[sourcecode language="javascript"]
getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US", function(){
FB.init("YOUR-API-HERE");
});

function getScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// most browsers
script.onload = callback;
// IE 6 & 7
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
callback();
}
}
document.getElementsByTagName('head')[0].appendChild(script);
}
[/sourcecode]