您应该以什么顺序列出 CSS 属性以获得最快的速度?

In what order should you list CSS properties for greatest speed?

让我们获取一些 CSS 属性并将它们随机放置在我们的 CSS 文件中:

outline
pseudo-elements
Color Properties
Background and Border Properties
Box Properties
Flexible Box Layout
Text Properties
Text Decoration Properties
Font Properties
Writing Modes
Table Properties
Lists
Animation


如果您想最大限度地提高渲染速度,应该按什么顺序列出您的 CSS 属性?

简短的回答是:没关系。

详细说明:假设您将实现一个浏览器1 并到达您解析CSS 的部分。你会怎么做?嗯,有一个 grammar of CSS, so you use that to tokenize the stylesheet, build an AST and parse 样式表。这种方法意味着您需要阅读所有内容2,然后才能开始真正解释 样式表。也就是说,将选择器应用于您的 DOM(也是您解析的内容,但来自 HTML 源而不是 CSS),然后将规则应用于与这些选择器匹配的元素。请注意,到目前为止我们所做的一切都只是修改数据结构的状态。我们在我们的元素上存储它们应该的样子。

完成后,layout phase can begin (and with modern CSS, that is even harder thanks to flexible box and grid layouts). It sounds simple: calculate where every element will end up on the page. It's not, but suppose that we are great programmers with a thorough understanding of the specifications that we need to adhere to, so we can do this. What do we need to know? Well, all rules that apply to all elements. It's as simple as that. We cannot calculate a layout to then learn from the parser that "oh wait, I forgot, this element all the way at the start of the HTML source is in fact positioned absolutely,所以你应该重新开始你的定位。所以,我们需要处理样式表中的所有内容。我们学习的顺序关于规则无所谓

好像这还不够,我们浏览器的下一阶段将是绘制所有内容,这又很重要。您对构建自己的浏览器感到兴奋吗?

如果您真的对主要浏览器如何实现所有这些感兴趣,您可以看看他们的引擎。我对那些完全不熟悉,但我知道它们是……令人生畏的。

所以,ye be warned.

• Chrome (Chromium) 使用 Blink (source code, forked from WebKit).
&子弹; Edge 使用 EdgeHTML (forked from Trident).
&子弹; Firefox 使用 Gecko (source code), but is working on a new engine called Servo (source code).
&子弹; Internet Explorer 使用 Trident.
&子弹; Opera 在 Opera 15 之前使用 Blink (used Presto
&子弹; Safari 使用 WebKit (source code).

我尽可能多地将 link 包含到源代码中,但某些浏览器引擎是专有的。 Presto 的源码前段时间泄露了,但我不会link 到这里。你也许能找到它。

免责声明:我只是触及了构建浏览器的皮毛。我还没有讨论交互性、实现 JavaScript 引擎、发出 HTTP 请求、调试工具、GUI 设计和实现等等。3 构建浏览器仅用于这个答案中的一个故事。如果您真的对构建浏览器感兴趣,请 考虑这些很棒的资源 4 不要。相反,为您最喜欢的浏览器的开发做出贡献,如果它是开源的!

想要阅读更多内容?
&子弹; This Mozilla Hacks article 很好地解释了渲染引擎的大致工作原理。
它还包括漂亮的图画!

____________________
1 你不想那样做。严重地。这是一项 很多 的工作。但是,说你愿意。
2 除非您愿意使用 AST 它是构建的。但这很难且容易出错。它最终也不会给你带来多少,我们稍后会看到。
3 this Mozilla Hacks blog post 中对此进行了更详细的讨论。
4从来没有过,这个post的修改历史不用查了。这只是个玩笑。
对不起,如果你觉得它很蹩脚。