Javascript 通过 jQuery 找到 body 标签的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7706429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to find the body tag via jQuery
提问by adam
On every document ready I need to get the body tag via jQuery and I'm more curious about the answer to this than anything else.
在准备好每个文档时,我需要通过 jQuery 获取 body 标签,我对此的答案比其他任何事情都更加好奇。
Let's say this is the body tag on every page on my site:
假设这是我网站上每个页面上的正文标记:
<body id="body">
Is it faster to query the body tag by just the tag name:
仅通过标签名称查询 body 标签是否更快:
$('body')
or query it by its id:
或通过其 id 查询:
$('#body')
回答by SLaks
回答by James Allardice
jQuery optimises the finding of the body
element. Here's the relevant jQuery source:
jQuery 优化了body
元素的查找。这是相关的jQuery 源代码:
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
So using $("body")
will be pretty much as fast as $(document.body)
, as suggested in other answers. Using $("body")
will certainly be faster than giving the body
an id
, because if an id
is used, the above, optimised code cannot run. jQuery will use getElementById
, which is fast, but not as fast as the above!
因此,正如其他答案中所建议的$("body")
那样$(document.body)
,使用速度将与 一样快。使用$("body")
肯定会比给出body
an更快id
,因为如果使用 an id
,上面的优化代码将无法运行。jQuery 会使用getElementById
,它很快,但没有上面的那么快!
Edit
编辑
As pointed out by @SLaks, $(document.body)
is the fastest, which makes sense when you look at the jQuery source that will handle a DOM element selector, rather than a string:
正如@SLaks 所指出的,$(document.body)
是最快的,当您查看将处理 DOM 元素选择器而不是字符串的 jQuery 源代码时,这是有道理的:
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
回答by Hyman
Tag name is the fastest in Chrome, and probably most browsers. Faster yet would be to skip the jQuery wrapper:
标签名称是 Chrome 中最快的,可能也是大多数浏览器中最快的。更快的是跳过 jQuery 包装器:
document.getElementsByTagName("body");
Or
或者
document.body