CSS 加载性能
Firefox 异步加载 CSS,也会异步渲染(无样式闪烁 FOUC,在 body 中的 元素后添加 script 标签【非空,加空格就行】阻塞渲染,它会等待 css 加载,这样就类似 edge,推荐渲染方式, blink 和 safari 只有 css 全部加载完才会渲染),但还是会阻塞后面 js 执行的(因为可以操作 DOM 和读取 CSSOM,所以 js 代码是在 css 加载之后执行的,比如 css 文件的 onload 的函数执行在后面 js 之前)!!!(console.log会执行)
CSS 加载不会阻塞 DOM 解析
CSS @import 串行加载,等 import 加载完才触发 的 load 事件
Problem:
- A browser can’t render a page until it has built the Render Tree;
- the Render Tree is the combined result of the DOM and the CSSOM;
- the DOM is HTML plus any blocking JavaScript that needs to act upon it;
- the CSSOM is all CSS rules applied against the DOM;
- it’s easy to make JavaScript non-blocking with async and defer attributes;
- making CSS asynchronous is much more difficult;
- so a good rule of thumb to remember is that your page will only render as quickly as your slowest stylesheet.
Summarise:
- Lazyload any CSS not needed for Start Render:
- This could be Critical CSS;
- or splitting your CSS into Media Queries.
- Avoid @import:
- In your HTML;
- but in CSS especially;
- and beware of oddities with the Preload Scanner.
- Be wary of synchronous CSS and JavaScript order:
- JavaScript defined after CSS won’t run until CSSOM is completed;
- so if your JavaScript doesn’t depend on your CSS;
- load it before your CSS;
- but if it does depend on your CSS:
- load it after your CSS.
- Load CSS as the DOM needs it:
- This unblocks Start Render and allows progressive rendering.