script关于async与defer属性的测试

环境:

  1. chrome31/firefox25/IE11(别的版本没有测试),以下简称chrome/firefox/IE
  2. http://127.0.0.1:8081/test1、http://127.0.0.1:8081/test2和http://127.0.0.1:8081/test3离别耽误5秒、3秒和马上,并会在控制台里打印test1、test2和test3

测试代码:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>script async defer</title>
<script type="text/javascript">
    window.onload = function() {
        console.log('onload');
    }
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded');
    });
</script>
<script type="text/javascript" src="http://127.0.0.1:8081/test1"></script>
<script type="text/javascript" src="http://127.0.0.1:8081/test2"></script>
<script type="text/javascript" src="http://127.0.0.1:8081/test3"></script>
</head>
<body>
</body>

nodejs做server:

var http = require('http');
http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    if (req.url == '/test1') {
        setTimeout(function() {
            res.end("console.log('test1');");
        }, 1000 * 5);
    } else if (req.url == '/test2') {
        setTimeout(function() {
            res.end("console.log('test2');");
        }, 1000 * 3);
    } else {
        res.end("console.log('test3');");
    }
    // res.end('Hello World\n');
}).listen(8081, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8081/'); 

测试步骤:

  1. 不为script设定defer或async时
    • 页面会在一切script加载和实行完后衬着 ,输出test1、test2和test3,DOMContentLoaded,onload
  2. 设置defer

    • test1为defer ,chrome/IE会等test2的3秒耽误后,控制台会马上输出test2和test3,等test1的5秒后会输出test1并触发DOMContentLoaded,末了触发onload;firefox会等test2的3秒耽误后,控制台会马上输出test2和test3并触发DOMContentLoaded,等test1的5秒后会输出test1,末了触发onload;
    • test1和test2都为defer时,chrome/IE会马上输出test3,只管test2比test1先加载完成然则只要比及test1加载完成实行后才继承实行,输出为test1和test2并触发DOMContentLoaded,末了触发onload;firefox会马上输出test3并触发DOMContentLoaded,test2下载完后等test1下载完并实行后才实行,输出test1和test2,末了触发onload
  3. 设置async

    • test1为async ,等test2的3秒耽误后,会马上输出test2和test3并触发DOMContentLoaded,等test1的5秒后会打印test1,末了触发onload
    • test1和test2都为async时 ,会马上输出test3并触发DOMContentLoaded,test2先加载完先打印test2,test1后加载完打印test1,末了触发onload

结论:

  1. 不设置async和defer时,页面会等script下载实行完后继承实行
  2. 设置defer时,会下载剧本,然则不会马上实行而且根据script递次触发
  3. 设置async时,会下载剧本,然则不会马上实行并不一定根据script递次触发
  4. 不管是不是设置了defer或async,该script会在onload前实行
  5. IE/chrome在设置defer时,与firefox差别,前者会等剧本都实行后才实行DOMContentLoaded,而后者会先于剧本实行
    原文作者:miser
    原文地址: https://segmentfault.com/a/1190000000339118
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞