What is the best way to inject a javascript script from another domain into a page? (without using a

Posted by lowellk on Stack Overflow See other posts from Stack Overflow or by lowellk
Published on 2010-04-28T23:10:33Z Indexed on 2010/04/28 23:17 UTC
Read the original article Hit count: 199

Filed under:

Here is a snippet of javascript for loading a script onto a given page asynchronously. I was wondering if there was anything wrong with it? Can it be improved?

I haven't played with this yet, but some things I'm worried about are: - cross browser support - when script.readyState is true, will the old version of that function get clobbered? - can i always count on there being a head or body element?

Here it is:

function injectScript(url, callback){
  var script = document.createElement('script');
  script.type = "text/javascript";
  script.setAttribute('async', 'true');
  script.src = url;

  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);

  if (callback) {
    if (script.readyState){
      script.onreadystatechange = function(){
        if(script.readyState === "loaded" || script.readyState === "complete"){
            script.onreadystatechange = null;
            callback();
        }
      };
    }else{ 
      script.onload = function() { 
        callback();
      }
    }
  }
}

© Stack Overflow or respective owner

Related posts about JavaScript