簡體   English   中英

加載外部 JS 並在同步后立即運行腳本

[英]Load external JS and run a script right after synchronously

我有這個 index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="src/index.js"></script>
    <script>
      alert("2");
    </script>
  </head>
  <body>
  </body>
</html>

和這個 index.js:

alert("1");

為什么alert('2')alert('1')
據我所知,加載src/index.js應該是一個阻塞操作。

https://codesandbox.io/s/kww2o7rm0v

謝謝

您可以使用 SetTimeout() 函數開始第二個警報,或者在退出警報時調用另一個腳本中的函數,使用:

alert("1");
// You could either put all of the other script in a function and call that here, or change the src of the script
document.GetElementById("ScriptID").src = "src/index.js";

希望我能幫上忙!

將腳本元素插入到文檔中可以伴隨一個onload回調函數以確保順序處理。 請參閱 Web/API/HTMLScriptElement 下的 Mozilla 發布的文檔 那里有說明和示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM