Heim  >  Fragen und Antworten  >  Hauptteil

Warten Sie, bis das Skript mit type="module" abgeschlossen ist, bevor Sie das nächste Skript ausführen

In meinem HTML-Dokument body 标记的底部,我有 2 个脚本标记,其中 type="module". Unten befindet sich ein Skript-Tag, das Einbettungscode enthält, der von den Ergebnissen der ersten beiden Skripte abhängt.

Gibt es eine Möglichkeit sicherzustellen, dass dieser Code erst ausgeführt wird, nachdem die ersten beiden Skripte abgeschlossen sind?

<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粉739706089P粉739706089244 Tage vor442

Antworte allen(1)Ich werde antworten

  • P粉127901279

    P粉1279012792024-02-18 10:42:18

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

    使用外部脚本文件:

    script.js

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

    使用 DOMContentLoaded 回调:

    Antwort
    0
  • StornierenAntwort