2012-03-15 150 views
1

我想从另一个 js文件调用外部js文件。这里是我的代码: “FUNC2没有定义”调用外部js文件

file1.js

function func1(id){ 
var NewScript= document.createElement('script') 
NewScript.src="file2.js" 
document.body.appendChild(NewScript); 
func2(id); 

} 

file2.js

function func2(id) 
{ 
    alert("im here " +id); 

} 

但是,当我跑了它给了 我在做它对?

有人可以帮我吗?

感谢

+0

这是一个假设的例子,你正在尝试,它不工作,或者这是你的真实代码?因为如果你的文件很大,你需要等待浏览器加载新的JS文件。 – Strelok 2012-03-15 06:19:28

+0

这不是真正的代码,我更改了文件名和file2.js,是的有点大.. – tinks 2012-03-15 06:21:08

+1

检查此:http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-文件 – 2012-03-15 06:21:11

回答

1

你必须等待脚本实际加载/解析。 .appendChild会立即返回,您的代码将继续运行,可能在浏览器有机会获取新脚本之前很长时间。

从.appendChild()移动到FUNC2()中的代码很可能是毫或微秒,而获取的脚本可能是整个秒,这取决于如何有损/ laggy网络当时行事。

+0

感谢您的!你是对的,我应该等待之前加载..我跟着Sudhir提供的链接的答案!多谢你们! – tinks 2012-03-15 06:43:56

0

import1.js:

var a = function() { 
    console.log('function a'); 

    this._require(function(){ 
     b(123456); 
    }); 
}; 

a.prototype._require = function (callback) { 
    var xhr = new XMLHttpRequest(); 

    xhr.onload = function (e) { 
     var script = document.createElement('script'); 
     script.innerHTML = e.target.responseText; 
     document.getElementsByTagName('head')[0].appendChild(script); 
     callback(); 
    }; 

    xhr.open('GET', 'import2.js', true); 
    xhr.send(); 
}; 

new a(); 

import2.js:

var b = function (id) { 
    console.log(id); 
}; 

结果:

**result**