前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【前端】:async、defer、onload、DOMContentLoaded

【前端】:async、defer、onload、DOMContentLoaded

作者头像
WEBJ2EE
发布2019-12-31 14:52:43
1.8K0
发布2019-12-31 14:52:43
举报
文章被收录于专栏:WebJ2EEWebJ2EEWebJ2EE

1. async、defer

1.1. 基础

The HTML <script> element is used to embed or reference executable code; this is typically used to embed or refer to JavaScript code.

不引入 defer、async 时

<script> 资源并行下载、按引入顺序执行

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
    <script type="text/javascript" src="delay2s.js"></script>
    <script type="text/javascript" src="delay1s.js"></script>
    <script type="text/javascript" src="delay4s.js"></script>
</head>
<body>
    <script type="text/javascript" src="delay3s.js"></script>
    <h1>defer-async</h1>
    <script>
        document.addEventListener('DOMContentLoaded',function(){
            console.log("DOMContentLoaded!");
        });
        window.onload = function(){
            console.log("onload!");
        }
    </script>
    <script type="text/javascript" src="delay8s.js"></script>
</body>
</html>

1.2. async

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Attributes

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
    <script type="text/javascript" src="delay2s.js" async></script>
    <script type="text/javascript" src="delay1s.js" async></script>
    <script type="text/javascript" src="delay4s.js" async></script>
</head>
<body>
    <script type="text/javascript" src="delay3s.js"></script>
    <h1>defer-async</h1>
    <script>
        document.addEventListener('DOMContentLoaded',function(){
            console.log("DOMContentLoaded!");
        });
        window.onload = function(){
            console.log("onload!");
        }
    </script>
    <script type="text/javascript" src="delay8s.js" async></script>
</body>
</html>

1.3. defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. Scripts with the defer attribute will execute in the order in which they appear in the document. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Browser_compatibility

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
    <script type="text/javascript" src="delay2s.js" defer></script>
    <script type="text/javascript" src="delay1s.js" defer></script>
    <script type="text/javascript" src="delay4s.js" defer></script>
</head>
<body>
    <script type="text/javascript" src="delay3s.js"></script>
    <h1>defer-async</h1>
    <script>
        document.addEventListener('DOMContentLoaded',function(){
            console.log("DOMContentLoaded!");
        });
        window.onload = function(){
            console.log("onload!");
        }
</script>
    <script type="text/javascript" src="delay8s.js" defer></script>
</body>
</html>

1.4. 总结

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

2. load、DOMContentLoaded?

2.1. DOMContentLoaded

当初始的 HTML 文档被完全加载和解析完成之后,DOMContentLoaded 事件被触发,而无需等待样式表、图像和子框架的完成加载注意:DOMContentLoaded 事件必须等待其所属script之前的样式表加载解析完成才会触发

兼容性:

行为模拟:

在IE8中,可以使用readystatechange事件来检测DOM文档是否加载完毕.在更早的IE版本中,可以通过每隔一段时间执行一次document.documentElement.doScroll("left")来检测这一状态,因为这条代码在DOM加载完毕之前执行时会抛出错误(throw an error)。

测试示例1:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
</head>
<body>
    <h1>defer-async</h1>
    <script>
        console.log(new Date());
        document.addEventListener('DOMContentLoaded',function(){
            console.log("DOMContentLoaded!", new Date());
        });
        window.onload = function(){
            console.log("onload!", new Date());
        }
    </script>
    <link rel="stylesheet" href="delay3s.css">
</body>
</html>

测试示例2:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
</head>
<body>
    <h1>defer-async</h1>
    <link rel="stylesheet" href="delay3s.css">
    <script>
        console.log(new Date());
        document.addEventListener('DOMContentLoaded',function(){
            console.log("DOMContentLoaded!", new Date());
        });
        window.onload = function(){
            console.log("onload!", new Date());
        }
    </script>
</body>
</html>

总结:

  • CSS 会阻碍 DOMContentLoaded;
  • CSS 会阻塞 JS 执行;

2.2. onload

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

兼容性:

2.3. jQuery.ready(fn) 源码摘录

API:

// jQuery offers several ways to attach a function 
// that will run when the DOM is ready. 
// All of the following syntaxes are equivalent:
$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )

源码摘录:

参考:

jQuery .ready() API: https://api.jquery.com/ready/ DOMContentLoaded: https://developer.mozilla.org/zh-CN/docs/Web/Events/DOMContentLoaded load: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event Google's opinionated reference for building amazing web experiences. https://developers.google.cn/web/fundamentals/performance/why-performance-matters async vs defer attributes https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html caniuse: https://caniuse.com/#search=async https://kinsta.com/blog/eliminate-render-blocking-javascript-css/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 WebJ2EE 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档