我有一个这样的 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>
您可以使用 async
或 defer
属性覆盖此行为。
async html5
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 adefer
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 中都不起作用,所以无论如何不要依赖脚本不按顺序执行。
引用:https://developer.mozilla.org/en/docs/Web/HTML/Element/script
关于javascript - 关于 html <script> 中的控制流顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20362598/