等待 type="module" 的脚本完成,然后再运行下一个脚本
P粉739706089
P粉739706089 2024-02-17 11:32:01
0
1
438

在我的 html 文档内的 body 标记的底部,我有 2 个脚本标记,其中 type="module"。下面有一个脚本标记,其中包含一些嵌入代码,这些代码取决于前两个脚本的结果。

有没有办法确保只有前两个脚本完成后才执行此代码?

<script src="./src/js/script1.js" type="module"></script>
<script src="./src/js/script2.js" type="module"></script>
<script type="text/javascript">
  // Code inside this tag should only run after the 2 previous script tags have been executed
  console.log('Hello SO');
</script>

P粉739706089
P粉739706089

全部回复(1)
P粉127901279

<script> 带有 type="module" 的标签会被自动赋予 defer 属性(参见 脚本的加载和执行顺序),所以为了让第三个标签在后面运行,它也需要推迟。由于内联脚本不可能做到这一点(如注释中所述),因此您可以将脚本移动到另一个文件并使用 src 属性引用它,或者将代码包装在 DOMContentLoaded 事件的事件侦听器中(请参阅 https://stackoverflow.com/a/41395202/19461620)

使用外部脚本文件:

sssccc

script.js

// Code inside this tag should only run after the 2 previous script tags have been executed
  console.log('Hello SO');

使用 DOMContentLoaded 回调:

sssccc
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!