document.head诉document.getElementsByTagName("head")[0] [英] document.head v. document.getElementsByTagName("head")[0]

查看:38
本文介绍了document.head诉document.getElementsByTagName("head")[0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 document.head 和使用 document.getElementsByTagName("head")[0] 有什么区别?我进行的测试表明,它们都需要大约一毫秒的时间.

What is the difference between using document.head and using document.getElementsByTagName("head")[0]? Tests I ran showed that they both take about a millisecond.

我也看到了

document.head||document.getElementsByTagName("head")[0];

这会让我相信 document.head 更快,而另一个更具兼容性,除了我所做的测试不支持这一点.

which would have led me to believe that document.head is faster and the other is more more compatible, except that the tests I did disproved this.

如果其中一个更兼容,为什么还要使用另一个?

And if one is more compatible, why use the other as well?

更新:正如某些人指出的那样,我的测试是错误的.

Update: My tests were wrong, as some have pointed out.

推荐答案

像这样使用 ||| 运算符是特征检测的一种形式.使用时,如果第一个值未定义,它将发回后一个值.

Using the || operator like that is a form of feature detection. When used, if the first value is undefined it sends back the latter value.

所以

document.head || document.getElementsByTagName("head")[0];

原因是,如果不支持 document.head ,则至少返回正确的值.

the reason is that if document.head is not supported at least the right value is returned.

至于速度测试,毫秒是很长的时间.我怀疑真的花了这么长时间.实际上,我做了一个 jsPerf .它表明 getElementsByTagName 函数的运行速度大约降低了80%.

As for your speed test, a millisecond is a long time. I doubt it really took that long. In fact, I made a jsPerf for this. It shows that the getElementsByTagName function is roughly 80% slower.

这篇关于document.head诉document.getElementsByTagName("head")[0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆