script中的async、defer区别

39 阅读1分钟

script有以下三类

<script src="xxx"></script>
<script src="xxx" async></script>
<script src="xxx" defer></script>
  1. script
  • 默认什么属性也没加也没有加,js的加载和解析会阻塞html文档的解析

    image.png

2、script async

  • js的下载是异步执行不会阻塞html的解析,但是js解析会阻塞

    image.png

3、script defer

  • js的下载和async一样,但是解析会等待html解析完,所以解析js也不会阻塞html的解析

    image.png

script标题js加载顺序js执行顺序
script同步执行阻塞html同步执行阻塞html
script async异步执行不阻塞html同步执行阻塞html
script defer异步执行不阻塞html等html解析完同步执行