css的!important規則對效能有影響嗎

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.