CSS 阻塞 I/O 初探

疑问 🤔

css 会阻塞 js 加载么?

JS放在底下会影响页面渲染吗?

打脸代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>kk<h1>
  <script>
    alert(1);
  </script>
</body>
</html>

可以看到,先弹出alert,再出现kk。

结论 🍺

script内嵌脚本/src 放在 Dom 底部不会影响 Dom解析,但是会影响Dom 渲染。

DOM 解析不影响,渲染依旧等待

CSS 会影响 Dom 渲染和解析吗

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    h1 {
      color:  red;
      font-size: 64px;
    }
  </style>
  <script>
    function h() {
      console.log(document.querySelectorAll('h1'));
    }
    setTimeout(h, 0);
  </script>
  <link rel="stylesheet" href="https://s3.pstatp.com/cdn/expire-1-M/angular-css/1.0.8/angular-css.js">
</head>
<body>
  <h1>kk<h1>
</body>
</html>

结论 🍺

需要弱网模式,调整chrome中,network,自定义网速为 10kb

所以:CSS不会影响Dom解析,但是会影响Dom渲染。

CSS 会影响 JS 吗

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    h1 {
      color:  red;
      font-size: 64px;
    }
  </style>
  <link
    rel="stylesheet"
    href="https://cdn.staticfile.org/twitter-bootstrap/5.0.0-alpha1/css/bootstrap-reboot.min.css"
  />
</head>
<body>
  <h1>kk<h1>
  <script>
    console.log('看看什么时候输出');
  </script>
</body>
</html>

结论 🍺

弱网模式

可以看到,等请求完css后,才会执行js。

因为js里面可能用到了某些类,做了重绘重排之类的事。所以要等CSS回来以后才会执行JS。

所以,CSS加载会阻塞后面JS脚本/语句

CSS 会影响 Dom ready 吗

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    h1 {
      color:  red;
      font-size: 64px;
    }
  </style>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      console.log('DOMContentLoaded');
    });
  </script>
  <link
    rel="stylesheet"
    href="https://cdn.staticfile.org/twitter-bootstrap/5.0.0-alpha1/css/bootstrap-reboot.min.css"
  />
</head>
<body>
  <h1>kk<h1>
  <script>
    console.log('it is me');
  </script>
</body>
</html>

结论 🍺

有时候不会影响,会时候会影响。 分两种:

  1. 当CSS后面没有JS时,不会影响。

  2. 当CSS后面还有JS时,会影响。理由跟第三问一样,怕JS中会用到CSS中的类,所以要等CSS请求回来解析后,才会解析。

Last Updated:
Contributors: kk