Load external Javascript on function call

耗尽温柔 提交于 2020-01-22 19:30:08

问题


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


回答1:


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



回答2:


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



回答3:


Get it with AJAX and then eval() the code.



来源:https://stackoverflow.com/questions/1375714/load-external-javascript-on-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!