In meinem HTML-Dokument body
標(biāo)記的底部,我有 2 個(gè)腳本標(biāo)記,其中 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>
<script>
帶有 type="module"
的標(biāo)簽會(huì)被自動(dòng)賦予 defer
屬性(參見(jiàn) 腳本的加載和執(zhí)行順序),所以為了讓第三個(gè)標(biāo)簽在后面運(yùn)行,它也需要推遲。由于內(nèi)聯(lián)腳本不可能做到這一點(diǎn)(如注釋中所述),因此您可以將腳本移動(dòng)到另一個(gè)文件并使用 src
屬性引用它,或者將代碼包裝在 DOMContentLoaded
事件的事件偵聽(tīng)器中(請(qǐng)參閱 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
回調(diào):