javascript 等待type=“module”的脚本完成后再运行下一个脚本

bnl4lu3b  于 2023-01-08  发布在  Java
关注(0)|答案(3)|浏览(267)

在我的html文档中的body标签的底部,我有两个带有type="module"的script标签,在它下面,我有一个script标签,其中嵌入了一些依赖于前两个脚本结果的代码。
有没有办法确保这段代码只在前两个脚本完成后才执行?

<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>
dgtucam1

dgtucam11#

使内联脚本成为模块1,并从那里获得所需的资源import

<script type="module">
  import result1 from "./src/js/script1.js";
  import result2 from "./src/js/script2.js";
  console.log('Hello SO');
</script>

Live example来源

iaqfqrcu

iaqfqrcu2#

您可以利用脚本的加载回调来确保顺序得到维护。

let scriptsLoaded = 0;

//script1
var script1 = document.createElement('script');
script.type = 'module';
script.src ='./src/js/script1.js';
document.head.appendChild(script);

//script2
var script2 = document.createElement('script');
script.type = 'module';
script.src ='./src/js/script2.js';
document.head.appendChild(script);

script1.onLoad = function () {
    scriptsLoaded++;
    if(scriptsLoaded == 2) //load third script
}

script2.onLoad = function () {
    scriptsLoaded++;
    if(scriptsLoaded == 2) //load third script
}
z4iuyo4d

z4iuyo4d3#

带有type="module"<script>标记会自动指定defer属性(参见load and execute order of scripts),因此要使第三个标记在后面运行,它也需要延迟。(正如评论中提到的),可以将脚本移动到另一个文件中,并使用src属性引用它,也可以将代码 Package 在DOMContentLoaded事件的事件侦听器中(参见https://stackoverflow.com/a/41395202/19461620
使用外部脚本文件:

<script type="text/javascript" src="./script.js" defer></script>

script.js

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

使用DOMContentLoaded回调:

<script type="text/javascript" >
    window.addEventListener('DOMContentLoaded', function() {
        (function($) {
            //do something with b-lazy plugin, lightbox plugin and then with flexslider
        })(jQuery);
    });
</script>

相关问题