gustavopaes
9/14/2012 - 4:37 PM

load a script, like a jsonp file, with callback and scope support

load a script, like a jsonp file, with callback and scope support

/**
 * Carrega um script e executa callback
 */
(function(window, document, head) {
  if(!window.loadScript) {
    window.loadScript = function(url, callback, scope, charset) {
      var sc     = document.createElement('script');
      sc.type    = 'text/javascript';
      sc.async   = true;
      sc.charset = charset || "utf-8";
      sc.src     = url;

      sc.onload = sc.onreadystatechange = (function(url, callback, scope, sc){
        return function(){
          if (!sc.readyState || sc.readyState == "loaded" || sc.readyState == "complete") {
            head.removeChild(sc);
            sc.onload = sc.onreadystatechange = null;
            if(typeof callback == "function") {
              callback.call(scope || null);
            }
          }
        }
      })(url, callback, scope, sc);

      head.insertBefore(sc, head.firstChild);
      return {"o":sc};
    }
  }
}(window, document, document.getElementsByTagName("head")[0]));