【问题标题】:How to wait until functions to be loaded inside script src tag using javascript如何等到使用javascript在脚本src标签内加载函数
【发布时间】: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");
};

我尝试了 settimeoutsetinterval 来避免上述问题,但是如果没有 settimeoutsetinterval 我有什么办法可以处理

无论如何我可以使用回调或 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


【解决方案1】:

这不是一个答案,但我相信这会对你有所帮助。

如果 jquery 它的锣是 $(document).ready(function(){}); 如果纯javascript参考以下链接:

click here

【讨论】:

  • 这不是正确的。在我的情况下,我有一个 emscrippten js 代码包含在一个名为:function module_calculation{ /*js code is here*/} 的函数中,并将其导出为:var Module_CalAlign = module_calculation();。我用普通的 jaavscript 函数写的,有没有我可以处理等到这个 module_calculation() 函数加载。
  • 可以试试这个stackoverflow.com/questions/10808109/script-tag-async-defer看看能不能帮到你
猜你喜欢
  • 2014-07-16
  • 2021-12-21
  • 1970-01-01
  • 2022-06-16
  • 2014-02-17
  • 1970-01-01
  • 2013-10-12
  • 2023-04-02
相关资源
最近更新 更多