最近思维里经常浮现的一些词是“优化”,“Web优化”,“Javascript优化”等等涉及到前端开发的优化技术。正如这个单词表达的“Front-end”,止于前端,一个网站产品最终的体现就是在浏览器内显示的界面上,这是从用户的角度来看待一个web产品的价值的一个方面,当然了,实用性和趣味性也是非常重要的一个方面。本人是搞前端开发,当然就会从浏览器的角度去思考问题。说到优化,前面的几篇文章谈到了一个方面的优化“提高页面的加载速度”,这个方面所涉及到的技术也是非常广阔的。下面来谈谈在css方面的一个优化。
以前写css的时候,都没有想到过css还能够优化,来加快页面样式的渲染速度。今天写这篇文章的思路是从这个问题开始的“浏览器是怎么解析css样式规则并且渲染页面elements的样式的?”,这个问题我也跟别人讨论过,终没结果,之后google出了一片mozilla的关于编写高效的css的文章,受益匪浅。揭开了我上面提到的那个问题,它是这样表述的:
The style system matches a rule by starting with the rightmost selector and moving to the left through the rule’s selectors. As long as your little subtree continues to check out, the style system will continue moving to the left until it either matches the rule or bails out because of a mismatch.
Your first line of defense is the rule filtering that occurs based on the type of the key selector. The purpose of this categorization is to filter out rules so that you don’t even have to waste time trying to match them. This is the key to dramatically increasing performance. The fewer rules that you even have to check for a given element, the faster style resolution will be. As an example, if your element has an ID, then only ID rules that match your element’s ID will be checked. Only class rules for a class found on your element will be checked. Only tag rules that match your tag will be checked. Universal rules will always be checked.
上面的两端En文道出了浏览器解析css样式规则的机制:浏览器样式系统是从右到左来解析每一条css样式规则,并且从HTML文档中查询elements,并且渲染样式的。En文不太好,翻译全部有些难度,请见谅。从这个机制出发,就可以体会到很多优化css的selectors优化方法了:
了解更多