描述:目前正在进行框架样式重构,发现用!important来重写花费时间在可控范围之内,那么问题来了,大量使用!important会对页面解析速度有影响吗?
百度&google了一大堆资料,发现浏览器对于html的解析大致是这样的:
if (aIsImportant) { if (!HasImportantBit(aPropID)) changed = PR_TRUE; SetImportantBit(aPropID); } else { // ...
并有专业人士给出了以下解释:
/** * 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 规则),使用的时候还要注意。
个人签名:己所不欲勿施于人