defer与async的认识

defer跟asyns都是脚本外联文件的标签属性(标签内的脚本不会执行),加了这两个属性其中一个那么脚本文件会异步加载执行。

首先检查defer在浏览器中执行顺序(检查浏览器为chome,firfox,ie)

defer:

在编译器中输入代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>defer async</title>
<style>
</style>
<script type="text/javascript">
  console.log("head内嵌js")
</script>
</head>
<body>
  <img src="../images/1.jpg" alt="1.jpg" onload="console.log('img')" />
  <script type="text/javascript" src="js/defer.js" defer="defer"></script>
  <script type="text/javascript">

    window.onload = function(){

      console.log("onload")
    
}

    console.log("内嵌js")
  </script>
</body>
</html>

在chome,firfox的控制台中,输出先后顺序为

head内嵌js
内嵌js
this is defer
img
onload
在ie的控制台中,输出先后顺序为

head内嵌js
img
内嵌js
this is defer

onload

defer要等到dom构造好了后再执行,所以'this is defer'会最后输出(上一篇文章对ie dom构造的理解是,dom中的所有资源下载后才能算构造好dom,不知道对不对?)
注:ie10中'内嵌js'先于'img';
 
从浏览器的输出结果可以看出,加defer的外联标签加载的文件,会在dom树构成后执行,onload是在dom树构成后并且所有资源(包括图片css,js)加载到浏览器后再执行。但会在document的DOMContentLoaded事件之前。
 
在w3c上看到,支持defer的浏览器有:

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The defer attribute is supported in all major browsers.

Note: The defer attribute is not supported in Opera 12 and earlier versions.
 
 
async:
这个属性跟defer一样,异步下载资源,不会堵塞浏览器渲染页面,然而这个属性跟defer不同的是,当该文件加载完后会立即执行该外联文件里面的脚本,不用等到dom树构造好。同时,几个加async的脚本下载后,按照先到先执行的顺序,不会按代码中的排列顺序执行,这点跟defer不一样.

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The async attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari.

Note: The async attribute of the <script> tag is not supported in Internet Explorer 9 and earlier versions.

 
posted @ 2014-05-12 16:54  outside  阅读(259)  评论(0编辑  收藏  举报