script标签async和defer执行顺序的问题?

<script async src="a.js"></script>
<script defer src="a.js"></script>

问下这两个文件哪个先执行?

阅读 2.2k
2 个回答
①<script async src="a.js"></script>
②<script defer src="a.js"></script>

①先执行,②后执行。 用给你说明理由吗?
①async
html发现了script标签

1.script下载,html文件继续加载
2.script下载结束以后。
3.html加载停止
4.script执行
5.html文件加载
   

②defer
html发现了script标签

1.script下载,html文件继续加载
2.script下载结束以后,html文件继续加载
3.html加载完了
4script执行

The script element:

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete.

For module scripts, if the async attribute is present, then the module script and all its dependencies will be fetched in parallel to parsing, and the module script will be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the module script and its dependencies will be fetched in parallel to parsing and evaluated when the page has finished parsing. (The defer attribute has no effect on module scripts.)

This is all summarized in the following schematic diagram:

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题