Load external javascript on function call

I would like to know how to load external Javascript into my document from a function.

+5
source share
3 answers

This is one way:

function loadDaFun() {
   var script = document.createElement('script');
   script.src = '/path/to/your/script.js';
   script.type = 'text/javascript';
   var head = document.getElementsByTagName("head")[0];
   head.appendChild(script);
}
+14
source

@Seth's answer is absolutely right, but you do not need to leave the inserted element scriptin the DOM, you can delete it immediately after it, and you can also find out when the inserted script is ready for use, for example, you can:

function loadScript(url, completeCallback) {
   var script = document.createElement('script'), done = false,
       head = document.getElementsByTagName("head")[0];
   script.src = url;
   script.onload = script.onreadystatechange = function(){
     if ( !done && (!this.readyState ||
          this.readyState == "loaded" || this.readyState == "complete") ) {
       done = true;
       completeCallback();

      // IE memory leak
      script.onload = script.onreadystatechange = null;
      head.removeChild( script );
    }
  };
  head.appendChild(script);
}

Using:

loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
            function () { alert('jQuery has been loaded.'); });
+11
source

AJAX, eval().

-2

All Articles