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.

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);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s