等待 type="module" 的腳本完成,然後再執行下一個腳本
P粉739706089
P粉739706089 2024-02-17 11:32:01
0
1
440

在我的 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學習者快速成長!