我有一些<script>元素,其中一些代码依赖于其他<script>元素中的代码。我看到defer属性在这里可以派上用场,因为它允许延迟代码块的执行。
为了测试它,我在Chrome上执行了这个:http://jsfiddle.net/xXZMN/。
<script defer="defer">alert(2);</script>
<script>alert(1)</script>
<script defer="defer">alert(3);</script>
然而,它提醒2 - 1 - 3。为什么它不提醒1 - 2 - 3?
<脚本延迟> -
只要浏览器使用defer与脚本标记进行交互
它开始获取脚本文件,同时还并排解析HTML。
在这种情况下,脚本只在HTML解析完成后执行。
<脚本async> -
当浏览器与async交互脚本标记时
它在并排解析HTML时开始获取脚本文件。
但是在完全获取脚本时停止HTML解析,然后开始执行脚本,之后继续进行HTML解析。
<脚本> - - -
只要浏览器与脚本标记交互
它停止HTML的解析,获取脚本文件,
在本例中,执行脚本,然后继续解析HTML。
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. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
延迟工作与chrome, firefox, ie > 7和Safari
裁判:https://developer.mozilla.org/en-US/docs/HTML/Element/script
<脚本延迟> -
只要浏览器使用defer与脚本标记进行交互
它开始获取脚本文件,同时还并排解析HTML。
在这种情况下,脚本只在HTML解析完成后执行。
<脚本async> -
当浏览器与async交互脚本标记时
它在并排解析HTML时开始获取脚本文件。
但是在完全获取脚本时停止HTML解析,然后开始执行脚本,之后继续进行HTML解析。
<脚本> - - -
只要浏览器与脚本标记交互
它停止HTML的解析,获取脚本文件,
在本例中,执行脚本,然后继续解析HTML。