[英]Calling external js file
我正在尝试从另一个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未定义。”我做对了吗?
有人可以帮我吗?
谢谢
您必须等待脚本被实际加载/解析。 .appendChild将立即返回,并且您的代码继续进行,很可能在浏览器有机会获取新脚本之前很长时间。
在代码中从.appendChild()移到func2()可能需要几毫秒或几微秒,而获取脚本可能需要整整几秒钟,具体时间取决于网络当时的有损/缓慢状态。
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 );
};
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.