最近在做項目中發現很多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/