$("body")是否使用Sizzle Engine?

Mat*_*rym 4 javascript jquery jquery-selectors sizzle

我知道它$("#id")更快,因为它映射到本机javascript方法.是真的$("body")吗?

Nic*_*ver 10

不,它没有使用Sizzle,有一个特殊的快捷方式$("body"),你可以在这里看到代码:

    // 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;
    }
Run Code Online (Sandbox Code Playgroud)

请注意,这是不是一样$(document.body),因为所得的背景$("body")document,那里的$(document.body)(像任何其他DOM节点)具有其自身的背景.


Cha*_*ion 6

这是源代码(代码):

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

对于身体以外的标签

如果你深入挖掘一下,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, $(...))
}
Run Code Online (Sandbox Code Playgroud)

  • **哇.**jQuery肯定有一些巧妙的伎俩. (3认同)