编程语言
首页 > 编程语言> > javascript – 在DOMContentLoaded事件之前执行延迟脚本吗?

javascript – 在DOMContentLoaded事件之前执行延迟脚本吗?

作者:互联网

推迟attirbute MDN says

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. The defer attribute should only be used on external scripts.

在DOMContentLoaded MDN also says上:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets

因此在CSSOM准备好之前就会触发DOMContentLoaded.这意味着在CSSOM准备好之前执行延迟脚本.但如果这是真的,那些scrips必须无法获得正确的css属性值,并且不能正确应用css.但事实并非如此,我们知道所有延迟脚本都能正常运行.

>那么MDN文档在技术上是不正确的吗?
>我在哪里可以找到DOMContentLoaded`的官方文档?我在https://dom.spec.whatwg.org/搜索但找不到它.

P.S:请不要在google says执行任何内联javscript之前构建CSSOM

enter image description here

但谷歌在技术上是不正确的.在CSSOM准备好之前,内联JavaScript会被执行.从我的测试中我发现MDN是正确的,如果在css文件(或js是内联)之前下载了js文件(延迟和非延迟),那么在CSSOM准备好之前执行js.所以js可能会错误地处理样式.为了避免这种情况,我们需要在所有js逻辑之前进行强制回流.

因此,如果用户访问我们的网站时所有需要缓存的js和css没有缓存,或者在css之前下载了js,那么他可能会看到错误渲染的页面.为了避免这种情况,我们应该在所有网站的js文件中添加强制重排.

解决方法:

DOMContentLoaded可以在CSSOM,source之前触发

The domContentLoaded event fires shortly after the HTML is parsed; the browser knows not to block on JavaScript and since there are no other parser blocking scripts the CSSOM construction can also proceed in parallel.

enter image description here

关于Google Developer的文章描述的是async而不是defer,但就您的问题而言,它不会改变任何内容,因为基于Steve Sourders article perfplanet

DEFER scripts execute after DOM Interactive.

his comment在他的文章下

[…] the spec says that DEFER scripts run after domInteractive but before domContentLoaded.

您可以进行自己的实验,使用延迟和时间线查看下面的代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.3/angular-material.css">
</head>
<body>
  <h1>App</h1>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.js" defer></script>
</body>
</html>

enter image description here

标签:html,javascript,css,dom,cssom
来源: https://codeday.me/bug/20190930/1835156.html