javascript - 关于 html <script> 中的控制流顺序

标签 javascript html

我有一个这样的 html 页面:

<!DOCTYPE HTML>
<html style="width: 100%; height: 100%">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
    </style>
</head>
<body style="height: 100%; width: 100%; margin: 0">
    <div id="outerParentDiv" style="width:100%; height: 100%;">  
    </div>
    <script src="<script1 - takes very long to download>">
     alert('hi1');
    </script>
    <script src="<script2 - takes very short to download>">
      alert('hi2');
    </script>
</body>
</html>

我可以假设流程是 - 下载脚本 1 >> 执行警报('hi1')>> 下载脚本 2 >> 执行警报('hi2') 或者它是特定于浏览器的 - 如果是,哪些浏览器做什么?

谢谢

最佳答案

浏览器很可能会同时下载这两个脚本(除非其中一个脚本已经被缓存),但执行顺序保证是有序的。此外,在脚本完成加载和执行之前,脚本后面的页面部分不会成为脚本的一部分。这确保您可以安全地在代码中包含库,并期望它们在主脚本开始运行时出现。

如前所述,您不应将 script 标签与 src 和自己的内容一起使用。

<script src = "http://path.to.a.cdn/jquery-latest.min.js"></script>
<script>
  $(function(){
    ...
  })
</script>

您可以使用 asyncdefer 属性覆盖此行为。

async

Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously. It has no effect on inline scripts (i.e., scripts that don't have the src attribute).

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute.

这两个属性在 IE 10 之前的 IE 中都不起作用,所以无论如何不要依赖脚本不按顺序执行。

兼容性表:async ; defer

引用:https://developer.mozilla.org/en/docs/Web/HTML/Element/script

关于javascript - 关于 html &lt;script&gt; 中的控制流顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20362598/

相关文章:

javascript - Javascript,暂停音频功能

javascript - 仅针对图像的 Google 自定义搜索

javascript - 为什么 Segment.io 加载程序脚本将方法名称/参数推送到一个看似被覆盖的队列中?

javascript - javascript中没有四舍五入的十进制比较

javascript - 尝试通过 javascript 将文本添加到我的输入中

html - <a href =""> 元素的最低样式是什么

javascript - 如果变量尚未传递给函数,则初始化该变量。这是正确的方法吗?

javascript - 如何禁用文本字段中的非罗马化字符和符号?

javascript - 网站联系表(网站吸盘网站)

javascript - 地铁 ui css tile 元素选择不起作用