简体   繁体   中英

Load external Javascript on function call

我想知道如何从函数中将外部Javascript加载到我的文档中。

This is one way:

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

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.'); });

使用AJAX获取它,然后使用eval()代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM