# 章序号/节序号/节/笔记序号 - Objective:执行脚本导致浏览器加载延时 # 概念阐释 HTML解析器在加载和执行`<script>`元素之前不会处理HTML文件中的下一个元素,因此导致加载时间延迟,从而导致用户体验不佳。HTML4引入了`defer`和`async`两个属性来解决这一问题。 ## 强调加载顺序 在html页面加载完成后执行 ```html <script src="example.js" defer></script> ``` ## 强调加载时间 加载后立即执行 ```html <script src="example.js" async></script> ``` # 举例子 ```html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <!-- Add the defer attribute to the script below: --> <script id="blue" src="turnBlue.js" defer></script> </head> <body> <p class="centered" id="logo">Codecademy</p> <script id="yellow" src="turnYellow.js"></script> </body> </html> ``` - 没加`defer`前的执行顺序 - 先执行蓝色字体,再执行黄色字体,最终显示为黄色 - 加`defer`后的执行顺序 - defer的规则是异步下载,在html页面加载完成后执行,所以最后执行蓝色字体,最早显示为蓝色 ```html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <!-- Add the async attribute to the script below: --> <script id="blue" src="turnBlue.js" async></script> </head> <body> <p class="centered" id="logo">Codecademy</p> </body> </html> ``` - async属性,js下载完立刻执行 # 类比、比较与对比 <table> <tr> <th></th> <th>下载</th> <th>顺序</th> <th>适用于</th> </tr> <tr> <th>defer</th> <td>异步下载</td> <td>html页面解析完成后执行脚本</td> <td>强调顺序</td> </tr> <tr> <th>async</th> <td>异步下载</td> <td>脚本下载完成后立刻执行</td> <td>不强调时间,优化页面加载时间</td> </tr> <tr> <th>无属性</th> <td>停止html页面后面的解析,先下载脚本</td> <td>下载后执行脚本,再继续解析后面的html页面</td> <td>强调顺序</td> </tr> </table> # 问题 # 问题答案 # 备注(经验集/错误集) ## summary 解决的怎么样? ## 参考资料