码迷,mamicode.com
首页 > 其他好文 > 详细

script defer和async一探

时间:2015-02-16 01:38:04      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

今天几经折腾,终于回家了,最近公司上的事忙了好一阵子,终于可以闲下来,重新在整理一下,又重新了解了一下defer和async在页面加载过程差异。

定义和用法

async 属性规定一旦脚本可用,则会异步执行。

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

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

  • 如果 async="async":脚本相对于页面的其余部分异步地执行(当页面继续进行解析时,脚本将被执行)
  • 如果不使用 async 且 defer="defer":脚本将在页面完成解析时执行
  • 如果既不使用 async 也不使用 defer:在浏览器继续解析页面之前,立即读取并执行脚本
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
        <script>

        window.onload = function(){
            console.log("window is loaded")
        }
        document.onreadystatechange = function(){
            console.log(document.readyState)
        }
        console.log("normal laod")
    </script>
</head>
<body>

    <script src="defer/a.js" defer></script>
    <script src="defer/async-defer.js" async defer></script>
    <script src="async/a.js" async></script>
    <script src="async/b.js" async></script>
    <script >
        console.log("last node")
    </script>
</body>
</html>

 

看一下在chrome中执行结果:

normal laod
index.html:24 last node
index.html:12 interactive
a.js:1 defer d
async-defer.js:1 async-defer
a.js:1 async a
b.js:1 async b
index.html:12 complete
index.html:9 window is loaded

执行顺序:

normal > defer > async-defer > async > complete > onload

看似好像都是这样顺序加载没有什么问题,其实在async中,并不是像现在这样看到的 async a async b;当文件加载大或者延迟,是会影响async加载结果。

script defer和async一探

标签:

原文地址:http://www.cnblogs.com/river-lee/p/4293624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!