当我在网上浏览关于CSS性能的文章时,我经常会发现有一个选择器比其他选择器更有效的列表。例如:
http://css-tricks.com/efficiently-rendering-css/
#main-navigation { } /* ID (Fastest) */
body.home #page-wrap { } /* ID */
.main-navigation { } /* Class */
ul li a.current { } /* Class *
ul { } /* Tag */
ul li a { } /* Tag */
* { } /* Universal (Slowest) */
#content [title='home'] /* Universal */我的问题是,当使用需要双选择器的选择器时,性能如何,例如:
.class-one.class-two {
}如果我们将这些选择器放在上面的性能列表中,它们会在哪里?
发布于 2013-09-17 21:59:34
发布于 2013-09-17 21:59:58
你不应该对那件事这么偏执。更重要的是有一个好的和干净的代码,避免黑客攻击。但有一些基本规则:
#main-navigation { } /* Never style ID's directly, use classes instead*/
body.home #page-wrap { } /* If you ever have to style ID's, do it directly, they are unique and doesn't need any selector. You're just wasting bytes */
.main-navigation { } /* No problem at all, but try to be more abstract. a class should not be so specific, try to reuse code as much as you can.*/
ul li a.current { } /* You should optimize this, you could use just ul .current. Try to use as little selectors as you can, it'll have good performance and will be easier to deal with. Try to use just 3 selectors at the max, so you''l have a good performance and clean code. */
ul { } /* No problem here */
* { } /* You'll won't have any serious problem if you use with caution. Properties like border-box are a good use of it. Anything that you have to set globally in your stylesheet is welcome to use it. */
#content [title='home'] /* Same as *. Don't overdo and you're good to go. */更重要的是拥有尽可能干净的代码。尽量避免过多的重写、未使用的代码、过多的选择器、重复的代码和hack。一件好事就是使用OOCSS和BEM。如果你使用一个框架,试着使用像inuit.css这样坚持良好实践的东西。
请记住,即使是智能手机现在也很强大,只要你不过度使用大量的动画,未经优化的代码,大量的javascript,你应该没有真正的问题。
附注:如果你使用动画,坚持使用CSS3过渡和动画,因为它们很可能会被图形处理器加速,并获得更好的性能。
发布于 2013-10-28 03:28:14
除了“编写高效的CSS”Mozilla的文章之外,你可能还会对Googlers http://www.youtube.com/watch?v=a2_6bGNZ7bA的演讲“更快的超文本标记语言和CSS:网页开发人员的布局引擎内部”感兴趣。
通常,浏览器从右到左读取每个选择器,然后“计算”它是否适用于当前的DOM节点。这就是为什么选择器以标签结尾或以许多级联结尾会导致性能问题,特别是在动态重新呈现的页面上。
如果遵循有关独立于的 CSS块的BEM CSS建议,则可以避免这种情况。http://bem.info/method/definitions/#IndependentCSS
https://stackoverflow.com/questions/18851392
复制相似问题