使用 jQuery 引用根 html 元素的最佳方法?

发布于 2024-11-19 18:41:34 字数 266 浏览 6 评论 0原文

在 jQuery 中获取根文档节点( 元素)的最佳方法(性能方面)是什么?我可以想到几种可能有效或无效的方法:

$("html")

$(document.documentElement)

$(document) (?)

$.root (?)

$.document (?)

Which is the best way (performance-wise) to get the root document node (the <html> element) in jQuery? I can think of several methods that may or may not work:

$("html")

$(document.documentElement)

$(document) (?)

$.root (?)

$.document (?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九命猫 2024-11-26 18:41:35

$(document.documentElement) 是最快的,有相当大的差距(请参阅测试此处)。

您可以通过查看 jQuery 源代码 更深入地了解为什么会出现这种情况(查看 init 函数,特别是处理 DOM 元素的部分和处理字符串的部分)。

$(document.documentElement) is the fastest, by quite some margin (see tests here).

You can get more insight as to why this is the case by looking at the jQuery source code (look at the init function, in particular, the part that handles a DOM element, and the part that handles a string).

行雁书 2024-11-26 18:41:35

我不认为它们真的有那么不同,但是 $("html") 似乎是最具可读性的,因此也是合乎逻辑的选择。

I don't think these are really that different, but $("html") seems the most readable, and therefore logical option.

转瞬即逝 2024-11-26 18:41:35

根据 Addy Osmani 的说法,idelement 选择器是最快的。

http://addyosmani.com/jqprovenperformance/

请参阅幻灯片 21 和 21 25.

所以我说 $("html")

同意 @AlienWebguy 的观点,您可以在 jsperf.com

According to Addy Osmani, id and element selectors are the quickest.

http://addyosmani.com/jqprovenperformance/

See slides 21 & 25.

So I say $("html")

Agree with @AlienWebguy that you can run your own tests on jsperf.com.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文