在加载函数调用外部JavaScript(Load external Javascript on fu

2019-08-03 15:41发布

我想知道如何在外部JavaScript加载到我的文档从功能。

Answer 1:

这是一种方式:

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


Answer 2:

该@seth的答案是完全正确的,但你并不需要离开插入script元素的DOM,你可以删除它,它加载刚过,也是你可能想知道什么时候插入脚本准备使用,例如,您可以:

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

用法:

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


Answer 3:

与AJAX获取它,然后eval()函数的代码。



文章来源: Load external Javascript on function call