2014-02-26 110 views
0

所以我正在瀏覽一些較老的jQuery發行說明,並發現這一點。爲什麼執行速度更快:使用offsetWidth和offsetHeight隱藏?

This is how the logic has changed: 
* In jQuery 1.3.1 (and older) an element was visible if its CSS 「display」 was not 「none」, its CSS 「visibility」 was not 「hidden」, and its type (if it was an input) was not 「hidden」. 
* In jQuery 1.3.2 an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0. 

在發行說明中,他們出於性能原因做了這些。

爲什麼要以這種方式改變實現會帶來這樣的性能好處?

你可以看到

http://blog.jquery.com/2009/02/20/jquery-1-3-2-released/

回答

0

那麼性能上的差異,他們基本上削減檢查次數。

v 1.3.1在檢查style.visibilitystyle.displaytype

v 1.3.2是隻檢查offsetWidthoffsetHeight屬性(我相信,在DOM實現 '緩存' 不知)

v 1.3.1:

Sizzle.selectors.filters.hidden = function(elem){ 
    return "hidden" === elem.type || 
    jQuery.css(elem, "display") === "none" || 
    jQuery.css(elem, "visibility") === "hidden"; 
}; 

Sizzle.selectors.filters.visible = function(elem){ 
return "hidden" !== elem.type && 
    jQuery.css(elem, "display") !== "none" && 
    jQuery.css(elem, "visibility") !== "hidden"; 
}; 

v 1.3.2

Sizzle.selectors.filters.hidden = function(elem){ 
    return elem.offsetWidth === 0 || elem.offsetHeight === 0; 
}; 

Sizzle.selectors.filters.visible = function(elem){ 
    return elem.offsetWidth > 0 || elem.offsetHeight > 0; 
}; 
相關問題