使用 jQuery 引用根 html 元素的最佳方法?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$(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).我不认为它们真的有那么不同,但是
$("html")
似乎是最具可读性的,因此也是合乎逻辑的选择。I don't think these are really that different, but
$("html")
seems the most readable, and therefore logical option.根据 Addy Osmani 的说法,
id
和element
选择器是最快的。http://addyosmani.com/jqprovenperformance/
请参阅幻灯片 21 和 21 25.
所以我说
$("html")
同意 @AlienWebguy 的观点,您可以在 jsperf.com。
According to Addy Osmani,
id
andelement
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.