【发布时间】:2020-01-13 03:55:01
【问题描述】:
我正在尝试使用 script src 加载其中一个 js 文件,但是此 src 文件中的函数(方法)总是需要时间来加载。 (注意:script 标签的 src="emscripten_model.js" 是在 emscripten 的帮助下生成的)。
我尝试使用下面的 function 和 callback ,但即使 src 中的方法尚未加载,也会调用回调函数。
this.loadModel = function(path,onloadCallback) {
let script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('type', 'text/javascript');
script.addEventListener('load', () => {
console.log("now ready to call callback!!!");
onloadCallback();
});
script.addEventListener('error', () => {
self.printError('Failed to load ' + path);
});
script.src = path;
let node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
console.log("ccccccccccccc");
};
我尝试了 settimeout 或 setinterval 来避免上述问题,但是如果没有 settimeout 或 setinterval 我有什么办法可以处理 。
无论如何我可以使用回调或 addeventlistener 更好地处理,请提供一段代码来解决这个问题。
【问题讨论】:
-
看起来你需要一个模块加载器。如果只有在现代浏览器中有asynchronously importing modules natively 的方式...
-
@BlueWater86,感谢您的指导。在我的情况下,我有一个 emscrippten js 代码包含在一个名为:function module_calculation{ /*js code is here*/} 的函数中,并将其导出为:var Module_CalAlign = module_calculation();。我用普通的 jaavscript 函数写的,有没有我可以处理等到这个 module_calculation() 函数加载。
标签: javascript jquery html addeventlistener