我有一个动态网页,我需要在另一个javascript文件内导入一个外部JS文件(在IF条件下)。

我试图寻找一个可行的解决办法,但没有成功。

我尝试使用document.createElement()将JS文件加载到DOM,但它也不起作用。显然,Js被加载到DOM中,但在当前Js文件中无法访问。

解决方案在jQuery也将很好


当前回答

我需要经常这样做,所以我使用这个:

var loadJS = function(url, implementationCode, location){
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to 
    //insert the <script> element

    var scriptTag = document.createElement('script');
    scriptTag.src = url;

    scriptTag.onload = implementationCode;
    scriptTag.onreadystatechange = implementationCode;

    location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);

有关更多信息,请参阅本网站如何在另一个JavaScript文件中包含一个JavaScript文件?,这是我的函数思想的来源。

其他回答

我猜在你的dom解决方案中,你做了如下的事情:

var script = document.createElement('script');
script.src = something;
//do stuff with the script

首先,这是行不通的,因为脚本没有被添加到文档树中,所以它不会被加载。而且,即使你这样做了,当另一个脚本正在加载时,javascript的执行仍在继续,所以它的内容在脚本完全加载之前是不可用的。

您可以侦听脚本的load事件,并按照您的意愿对结果进行处理。所以:

var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes

jQuery有$.getScript():

描述:使用GET HTTP请求从服务器加载一个JavaScript文件,然后执行它。

我建议使用AMD javascript类文件requirejs

这是一个很好的例子

http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/

如果你有很多依赖文件,使用AMD/RequireJS。 http://requirejs.org/

你可以动态加载页面内的js,而不是另一个js文件。

你必须使用getScript来加载js文件。

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
  console.log(data); // data returned
  console.log(textStatus); // success
  console.log(jqxhr.status); // 200
  console.log('Load was performed.');
});