我正在尝试从另一个js文件调用外部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);
}但是当我运行它的时候,它给出了"func2没有定义“。我做得对吗?
有人能帮帮我吗?
谢谢
发布于 2012-03-15 14:20:22
您必须等待脚本实际加载/解析。.appendChild将立即返回,您的代码将继续执行,很可能是在浏览器有机会获取新脚本之前很久。
在代码中从.appendChild()转移到func2()可能需要几毫秒或几微秒,而获取脚本可能需要整整几秒,这取决于当时网络的损耗/滞后程度。
发布于 2017-04-18 19:17:40
导入1.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();导入2.js:
var b = function ( id ) {
console.log( id );
};结果:

https://stackoverflow.com/questions/9714825
复制相似问题