微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – “使用高效的CSS选择器”规则发生了什么变化?

Google PageSpeed提出了一项建议,要求网络开发人员使用 Use efficient CSS selectors

Avoiding inefficient key selectors that match large numbers of
elements can speed up page rendering.

Details

As the browser parses HTML,it constructs an internal document tree
representing all the elements to be displayed. It then matches
elements to styles specified in varIoUs stylesheets,according to the
standard CSS cascade,inheritance,and ordering rules. In Mozilla’s
implementation (and probably others as well),for each element,the
CSS engine searches through style rules to find a match. The engine
evaluates each rule from right to left,starting from the rightmost
selector (called the “key”) and moving through each selector until it
finds a match or discards the rule. (The “selector” is the document
element to which the rule should apply.)

According to this system,the fewer rules the engine has to evaluate
the better. […]. After that,for pages that contain large numbers of
elements and/or large numbers of CSS rules,optimizing the deFinitions
of the rules themselves can enhance performance as well. The key to
optimizing rules lies in defining rules that are as specific as
possible and that avoid unnecessary redundancy,to allow the style
engine to quickly find matches without spending time evaluating rules
that don’t apply.

此建议已从当前的Page Speed Insights rules删除.现在我想知道为什么删除此规则.在此期间,浏览器是否能够有效地匹配CSS规则?这个建议是否有效?

解决方法

2011年2月,Webkit核心开发人员Antti Koivisto made several improvements将Webkit中的CSS选择器性能提升.

Antti Koivisto taught the CSS Style Selector to skip over sibling selectors and faster sorting,which bring some minor improvements,after which he landed two more awesome patches: one which enables ancestor identifier filtering for tree building,halving the remaining time in style matching over a typical page load,and a fast path for simple selectors that speed up matching up another 50% on some websites.

Nicole Sullivan的CSS Selector Performance has changed! (For the better)更详细地介绍了这些改进.综上所述 –

According to Antti,direct and indirect adjacent combinators can still be slow,however,ancestor filters and rule hashes can lower the impact as those selectors will only rarely be matched. He also says that there is still a lot of room for webkit to optimize pseudo classes and elements,but regardless they are much faster than trying to do the same thing with JavaScript and DOM manipulations. In fact,though there is still room for improvement,he says:

“Used in moderation pretty much everything will perform just fine from the style matching perspective.”

虽然浏览器在匹配CSS选择器方面要快得多,但值得重申的是CSS选择器仍应进行优化(例如尽可能保持“平坦”)以减小文件大小并避免特殊性问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐