簡體   English   中英

HTML 文檔中多個腳本的運行順序?

[英]Running order of multiple scripts in an HTML document?

我有一個發送到瀏覽器的 HTML 頁面,它包含幾個腳本標記。

這是我的index.html文件:

  <body>
    <div id="app"></div>

    <script src="src/index.js"></script>

    <script>
      window.test = true;
    </script>
  </body>
</html>

這是我的src/index.js文件:

<script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};

test();
</script>

在 HTML 文件中,我在運行src/index.js定義了window.test src/index.js僅在window.test設置為true時才會打印到控制台,但僅在之后設置為第二個腳本。

這些腳本的運行順序是什么? 是否可以保證window.test始終設置為true ,以便src/index.js中的if語句打印wow!

代碼沙盒: https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

在從 HTML 文件調用的 JS 中,腳本的順序就像它們在該文件中的寫入順序一樣,“始終”將按該順序排列,這意味着在您的示例window.test中, index.js中的值始終為 null 所以控制台中不會打印任何內容

保證測試 function 僅在設置變量后調用為什么不使用自定義事件

<script src="src/index.js"></script>

<script>
  window.test = true;
  const event = new Event('test-setted');
  document.dispatchEvent(event);

</script>

在 index.js 中

<script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};
document.addEventListener('test-setted', function (e) { 
    test(); 
}, false);

</script>

暫無
暫無

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

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