<script> 的defer和async

<script src="../file.js" async="async"></script>

file.js----

仅仅只有alert("hello,world");

 

async 属性仅适用于外部脚本(只有在使用 src 属性时)。

有多种执行外部脚本的方法:

  • 如果 async="async":脚本相对于页面的其余部分异步地执行(当页面继续进行解析时,脚本将被执行)
  • 如果不使用 async 且 defer="defer":脚本将在页面完成解析时执行
  • 如果既不使用 async 也不使用 defer:在浏览器继续解析页面之前,立即读取并执行脚本
<html> 
 <head> 
<script type="text/javascript" src="file.js" async="async"></script> 
</head>
<body>
<div style="height:100px;100px;background-color:#000000">
</div>

 </body> 
</html>

 在IE8下执行代码并没有体现异步的功能,执行顺序为:

(1)弹出 hello,world

(2)关闭 "hello,world"后渲染BOM界面

将相同的代码在chorme中进行执行,体现异步特性,即弹出hello,world和渲染浏览器同时进行

关闭【确定】按钮后执行页面如下:

在chorme下的执行结果如下:

原文地址:https://www.cnblogs.com/CBDoctor/p/3952343.html