Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external Javascript on function call

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

like image 663
Ronal Avatar asked Sep 03 '09 20:09

Ronal


People also ask

How do you call a function from an external JavaScript file?

Calling a function using external JavaScript file Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.


1 Answers

The @seth's answer is completely right, but you don't need to leave the inserted script element on the DOM, you can remove it just after it is loaded, and also you might want to know when the inserted script is ready to 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);
}

Usage:

loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
            function () { alert('jQuery has been loaded.'); });
like image 111
Christian C. Salvadó Avatar answered Nov 02 '22 04:11

Christian C. Salvadó