CSS and Network Performance
Despite having been called CSS Wizardry for over a decade now, there hasn’t been a great deal of CSS-related content on this site for a while. Let me address that by combining my two favourite topics: CSS and performance.
儘管已經被稱為 css 魔法十多年了, 但在網站上一段時間以來, 與css 相關的內容已經不多了。讓我通過結合我最喜歡的兩個主題來解決這個問題: css 和效能。
CSS is critical to rendering a page—a browser will not begin rendering until all CSS has been found, downloaded, and parsed—so it is imperative that we get it onto a user’s device as fast as we possibly can. Any delays on the Critical Path affect our Start Render and leave users looking at a blank screen.
CSS 對於渲染頁面是至關重要的,瀏覽器只有等 CSS 全部載入和解析完全以後才會開始渲染。所有,在使用者的介面上儘快的顯示就是必要的,任何在關鍵頁面的延遲都會影響開始渲染的程序,這會導致使用者看到一個空白的螢幕
What’s the Big Problem
最 嚴重 的問題
Broadly speaking, this is why CSS is so key to performance:
從廣義上講, 這就是為什麼 css 是效能的關鍵:
- 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
anddefer
attributes; - making CSS asynchronous is much more difficult;
- so a good rule of thumb to remember is thatyour page will only render as quickly as your slowest stylesheet .
- 瀏覽器在構建 Render Tree 前無法渲染頁面
- Render Tree 是結合 DOM 和 CSSDOM 的結果
- DOM 是 HTML 加上任何對其執行不阻塞的 js
- CSSDOM 是適用於所有的 DOM 規則
- 使用非同步和延遲屬性很容易使 javascript 不阻塞;
- 要使 css 非同步要困難得多;
- 因此, 需要記住的一個很好的經驗法則是, 您的頁面的渲染速度只能與載入最慢的樣式表一樣快
With this in mind, we need to construct the DOM and CSSOM as quickly as possible. Constructing the DOM is, for the most part, relatively fast: your first HTML response is the DOM. However, as CSS is almost always a subresource of the HTML, constructing the CSSOM usually takes a good deal longer.
出於這個目的,我們需要儘可能快的構建 DOM 和 CSSDOM。大多數情況下,構建 DOM 是很快的,第一個 HTML 響應就是 DOM,然而,CSS 總是作為 HTML 的子資源,構建 CSSDOM 通常需要花費更長的時間
In this post I want to look at how CSS can prove to be a substantial bottleneck (both in itself and for other resources) on the network, and how we can mitigate it, thus shortening the Critical Path and reducing our time to Start Render.
在這篇文章中, 我想看看 css 如何能夠證明是一個實質性的瓶頸 (本身和其他資源) 上的網路, 以及我們如何可以減輕它, 從而縮短關鍵路徑和減少我們的時間開始渲染。