css的!important规则对性能有影响吗

      最近在做项目中发现很多CSS代码里面都使用!important去覆盖原有高优先级的样式。按照常理来说,越是灵活的东西,需要做的工作就会更多。所以想当然的认为像!important这样灵活、方便的规则如果用得多的话肯定会对性能有所影响。基于这种考虑,本来想把所有的这些样式通过提高优先级给去掉的。不过后来一想,还是去google一下吧,猜想一般都是不可靠的。于是查到了这篇文章Is !important bad for performance?。下面是大概意思:

       firefox对于CSS的解析代码/source/layout/style/nsCSSDataBlock.cpp#562对于important的处理是这样的:

if (aIsImportant) {
    if (!HasImportantBit(aPropID))
      changed = PR_TRUE;
    SetImportantBit(aPropID);
  } else {
    // ...

source/layout/style/nsCSSDataBlock.h#219这里面有条评论算是对上面代码的解释:

 /**
     * Transfer the state for |aPropID| (which may be a shorthand)
     * from |aFromBlock| to this block.  The property being transferred
     * is !important if |aIsImportant| is true, and should replace an
     * existing !important property regardless of its own importance
     * if |aOverrideImportant| is true.
     * 
     * ...
     */

      从上面可以看出,firefox对于!important规则的判断很简单:将包含!important的样式直接覆盖了正常生成的样式规则,然后如果解析到后面还有!important规则时,再和以前的important规则比较优先级。就是说,使用!important的CSS规则是置为了最高优先级,然后最高优先级中去判断应用那个样式。

    

      结论就是,使用!important对于性能并没有什么负面影响。但是从可维护性角度考虑还是少用这个规则。不过这个规则在IE6中有bug(IE6 IE7(Q) IE8(Q) 不完全支持 !important 规则),使用的时候还要注意。

参考文章:

https://developer.mozilla.org/zh-CN/docs/Web/CSS/Specificity

http://www.w3cplus.com/css/the-important-css-declaration-how-and-when-to-use-it.html

http://www.w3.org/TR/CSS2/cascade.html#important-rules

http://w3help.org/zh-cn/causes/RA8003

http://stackoverflow.com/questions/13743671/is-important-bad-for-performance

http://www.html5rocks.com/zh/tutorials/internals/howbrowserswork/

原文地址:https://www.cnblogs.com/shinnyChen/p/3758166.html