这是我用来在我的超文本标记语言页面中动态包含带有src
的脚本标记的代码。在这个新导入的javascript文件中有一个我想使用的函数:
var scriptFile= document.createElement("script");
scriptFile.src = "something.js";
var something=document.body.appendChild(scriptFile);
something.js包含一个名为doSomething()
的函数。现在,当我在上面的appendChild
之后立即调用此函数时,它会显示未定义doSomething
。但是,当我从Chrome控制台启动它时,它成功执行了。我不确定为什么会发生这种情况。
发布于 2018-06-08 01:59:39
当你用源代码附加script
标签时,首先会对源代码进行解析和编译,这是一个异步过程(非阻塞)。
如果您尝试立即调用该方法,则会抛出一个错误,因为源代码尚未编译。
绑定一个在脚本可用时触发的load
事件。这将确保您仅在完全加载之后才运行script标记的内容。
var scriptFile= document.createElement("script");
scriptFile.addEventListener('load', function() {
console.log('Script is ready to execute');
// invoke your function here
});
scriptFile.src = "something.js";
var something=document.body.appendChild(scriptFile);
发布于 2018-06-08 01:59:44
侦听onload
var scriptFile= document.createElement("script")
scriptFile.src = "something.js"
document.body.appendChild(scriptFile)
scriptFile.onload = () => {
// call something.js functions here
}
https://stackoverflow.com/questions/50747404
复制相似问题