为什么实现起来更快:使用offsetWidth和offsetHeight隐藏?

时间:2014-02-26 19:59:53

标签: javascript jquery performance dom

所以我正在查看一些较旧的jquery发行说明,并发现了这一点。

    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/

1 个答案:

答案 0 :(得分: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;
};