首页 > 解决方案 > 加载外部 JS 并在同步后立即运行脚本

问题描述

我有这个 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

谢谢

标签: javascript

解决方案


您可以使用 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";

希望我能帮上忙!


推荐阅读