动态加载的JavaScript在完全加载JS文件之前开始执行
我正在动态地添加带有以下功能的脚本:
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);
}
加载的脚本呼叫函数在它们之后定义。当我通常添加到HTML时,它们运行良好。但是,如果我使用上述功能动态添加脚本,则它给出了未定义的错误,用于调用呼叫后定义的呼叫函数。
随着登录动态脚本负载,我看到(动态添加的)脚本在完全加载文件之前就开始执行。因此,未定义的错误是在“加载:”日志之前出现的。
我试图关闭异步加载,然后推迟。仍然同样的问题。
编辑:
延期现在有效。脚本按顺序加载。然而,未定义的错误仍在继续。
jQuery(...).hover3d is not a function
Hover3D在同一文件中定义了错误。
I am dynamically adding scripts with the function below:
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. But if i add scripts dynamically with the above function, it gives undefined error for calling functions defined after the call.
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在评论中解释了所有内容,所以首先阅读
我不确定它会起作用!
谢谢你!
I explained everything in comments so read it first
I am not 100% sure that this will work!
Thank you!