gpt4 book ai didi

javascript - 在主流浏览器中无法保证 JavaScript <script> 标记执行的顺序?

转载 作者:行者123 更新时间:2023-12-02 22:41:03 26 4
gpt4 key购买 nike

在主要浏览器中是否不能保证以下脚本标记始终按声明顺序执行?即我是否应该假设以下代码并不总是在警报中产生 x == 'ab' ?

<head>
<script type="text/javascript">
//tag A
var x = x || ''; x += 'a';
</script>
<script type="text/javascript">
//tag B
var x = x || ''; x += 'b';
</script>
</head>
<body>
<script type="text/javascript">
alert('x='+x);
<script>
</body>

...x 可能会是以下之一:

  1. 'ba' - 如果标签 B 在 A 之前执行
  2. 'a' 或 'b' - A 和 B 并行执行的竞争条件(虽然看起来像 this 线程清楚地表明浏览器只分配单个 JS 线程)

最佳答案

这些非动态添加的执行顺序script标签应该纯粹是 sequentially在每个浏览器中:

来自this link的片段:

JavaScript statements that appear between <script> and </script> tags are executed in order of appearance; when more than one script appears in a file, the scripts are executed in the order in which they appear.

但是,一旦您执行以下操作,情况就会发生变化:

关于javascript - 在主流浏览器中无法保证 JavaScript &lt;script&gt; 标记执行的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com