- 
                Notifications
    You must be signed in to change notification settings 
- Fork 11
Description
<script>标签中的defer与async属性
HTML4为<script>标签定义了一个扩展的属性:defer,指明本元素所含的脚本不会修改DOM的结构,因此代码能够安全的延迟执行
<script>脚本中没有defer或者async脚本,浏览器会立即下载并且执行指定的脚本,也就是阻塞后续加载的元素,读取到就立刻加载并且执行
<script async>下载此脚本的内容同后续文档的加载与渲染异步, 一旦下载完成,立即执行
<script defer>下载此脚本的内容同后续文档的加载和渲染异步,执行拖延到后续文档都加载渲染完毕
执行时间:
DOMContentLoaded时事件触发之前
另外一点需要注意的,根据浏览器的最新规范要求,defer属性只有当定义了src属性的<script>才有效
<script defer="defer">alert(2);</script>
<script>alert(1)</script>
<script defer="defer">alert(3);</script>预想中的执行过程应该是1-2-3 但是实际上是2-1-3 ,原因就是defer属性压根无效
Refer: How exactly does <script defer=“defer”> work?
The defer and async attributes must not be specified if the src attribute is not present.
如果script标签没有src属性,那么defer与async属性不生效
There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
使用async和defer有三个模式,如果async属性存在,那么script标签将会被尽可能快的异步执行.如果async属性没有存在,但是defer属性存在,那么script脚本将会在页面加载完成后被执行.如果这defer与async都没有存在,那么脚本将会在下载后立即被执行(阻塞页面其他资源的下载与解析)
