[英]How to ensure Javascript file loads after event listener triggers?
I currently have an event listener that listens for something to trigger.我目前有一个事件侦听器,用于侦听要触发的内容。 I would like for the event to trigger before trying to load the js file.
我希望在尝试加载 js 文件之前触发该事件。 Right now the JavaScript is loading and then the api is ready.
现在 JavaScript 正在加载,然后 api 就准备好了。 How can I get the EventListener to fully complete before the main.js file loads?
如何在加载 main.js 文件之前让 EventListener 完全完成?
<head>
<title>Default</title>
<script>document.addEventListener(apikey,function () {
console.log("ready");
});
</script>
<script src="./js/main.js"></script>
<script>console.log("js loaded")</script>
</head>
Remove the script tag to main.js.将 script 标签移除到 main.js。
Inside your event listener function, create and add a script tag to the document:在您的事件侦听器函数中,创建一个脚本标记并将其添加到文档中:
Your code should look like:您的代码应如下所示:
<head>
<title>Default</title>
<script>
document.addEventListener(apikey, function() {
const myscript = document.createElement('script');
myscript.src = './js/main.js';
document.body.appendChild(myscript);
});
</script>
<script>
console.log("js loaded")
</script>
</head>
You can do something like this:你可以这样做:
<head>
<link href="./js/main.js" rel="preload" as="script">
<script>
async function runScript(src) {
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
document.addEventListener(apikey, () => {
runScript('./js/main.js');
});
</script>
</head>
The advantage of this approach is that the script will start loading immediately, regardless of the event.这种方法的优点是脚本将立即开始加载,而不管事件如何。 And it can be called from the event without wasting extra time.
并且可以从事件中调用它而不会浪费额外的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.