[英]Dynamically loaded javascript starts executing before loading js file fully
I am dynamically adding scripts with the function below:我正在使用下面的 function 动态添加脚本:
function loadScript(scriptUrl) {
const body = this.document.getElementsByTagName('body')[0];
const script = this.document.createElement('script');
script.id = elmName;
script.src = `${scriptUrl}`;
script.async = false;
script.defer = true;
script.onload = () => {console.log("LADEDED: " + scriptUrl);}
body.appendChild(script);
}
The loaded scripts call functions that are defined after them.加载的脚本调用在它们之后定义的函数。 They work well when i normally add to html.当我通常添加到 html 时,它们运行良好。 But if i add scripts dynamically with the above function, it gives undefined error for calling functions defined after the call.但是,如果我使用上述 function 动态添加脚本,则会在调用后定义调用函数时出现未定义的错误。
With the logging on dynamic script load, i saw that (dynamically added) scripts starts executing before their file is fully loaded.通过动态脚本加载的日志记录,我看到(动态添加的)脚本在其文件完全加载之前开始执行。 Thus the undefined error comes before "LOADED:" log.因此未定义的错误出现在“LOADED:”日志之前。
I tried to turn async loading off, and defer.我试图关闭异步加载并推迟。 Still same problem.还是一样的问题。
EDIT:编辑:
Defer works now.延迟现在有效。 Scripts load in order.脚本按顺序加载。 Yet the undefined errors continues.然而,未定义的错误仍在继续。
jQuery(...).hover3d is not a function
hover3d is defined at the same file the error occurs. hover3d 是在发生错误的同一文件中定义的。
I explained everything in comments so read it first我在评论中解释了所有内容,因此请先阅读
// make normal function to arrow function according es6 syntax
const loadScript = (URL, elemName) => {
// return a promise to handle time error
return new Promise((res, rej) => {
// try and catch block to handle any kind of err
try {
// create a script element
const script = document.createElement("script");
// a simple way to set attributes according to me
Object.assign(script, {
id: elemName,
src: URL,
});
// whenever the script load this function will fire and resolve promise until .then will not fire so add function never call before.
script.addEventListener("load", () => res(`Loaded: ${URL}`));
// append script into body
document.body.appendChild(script);
} catch (err) {
// reject promise with err
rej(err);
}
});
};
loadScript("./math.js", "mathScript").then(() => {
// call add function from another script
add();
});
I am not 100% sure that this will work Thank you我不是 100% 确定这会起作用 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.