【问题标题】:Does $("body") use Sizzle Engine?$("body") 是否使用 Sizzle 引擎?
【发布时间】:2011-05-23 02:27:33
【问题描述】:

我知道$("#id") 更快,因为它映射到原生 javascript 方法。 $("body")也一样吗?

【问题讨论】:

    标签: javascript jquery jquery-selectors sizzle


    【解决方案1】:

    这是直接来自source (code)

    if ( selector === "body" && !context && document.body ) {
        this.context = document;
        this[0] = document.body;
        this.selector = "body";
        this.length = 1;
        return this;
    }
    

    对于正文以外的标签

    如果你再深入一点,如果没有给出上下文,他们会使用getElementsByTagName。与使用 Sizzle 引擎相比,这将大大提高性能。

    // HANDLE: $("TAG")
    } else if ( !context && !rnonword.test( selector ) ) {
        this.selector = selector;
        this.context = document;
        selector = document.getElementsByTagName( selector );
        return jQuery.merge( this, selector );
    
    // HANDLE: $(expr, $(...))
    }
    

    【讨论】:

    • @BoltClock - 这实际上是一个非常合乎逻辑的优化。
    • @ChaosPandion - 您更新的答案不正确,如果没有给出上下文,第一个版本会运行,前提是 <body> 存在(它将在 document.ready 上)。
    • @Nick - 你能更详细地解释你认为不正确的地方吗?
    • @ChaosPandion - 这是不正确的,if ( selector === "body" && !context && document.body ) {true 如果没有给出上下文,那是使用的代码,而不是元素选择器分支。
    • @Nick - 我的编辑应该让答案更加清晰。
    【解决方案2】:

    不,它不使用 Sizzle,$("body") 有一个特殊的快捷方式,you can see the code here

        // The body element only exists once, optimize finding it
        if ( selector === "body" && !context && document.body ) {
            this.context = document;
            this[0] = document.body;
            this.selector = "body";
            this.length = 1;
            return this;
        }
    

    请注意,这与$(document.body) 不同完全,因为$("body") 的结果上下文是document,而$(document.body)(与任何其他DOM 节点一样)具有自身的上下文。

    【讨论】:

    • $("body.class") 是否使用嘶嘶声?因此我应该使用 $("body").filter(".class")... 还是什么?
    • @Matrym - 较新的浏览器不会太在意,它们会使用原生选择器方法,例如querySelectorAll()。但要直接回答,$("body.class") 或任何变体 except $("body") 都没有经过特殊处理,因此会被转储到选择器引擎。
    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 2011-03-17
    • 2021-09-23
    • 2015-05-23
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多