使用document.head
和使用document.getElementsByTagName("head")[0]
有什么区别?我进行的测试表明,它们都需要大约一毫秒的时间。
我也看过
document.head||document.getElementsByTagName("head")[0];
这会让我相信
document.head
更快,而另一个更加兼容,除了我确实反对的测试。如果一个更兼容,为什么还要使用另一个呢?
更新:正如某些人指出的,我的测试是错误的。
最佳答案
像这样使用||
运算符是特征检测的一种形式。使用时,如果第一个值未定义,它将发回后一个值。
因此对于
document.head || document.getElementsByTagName("head")[0];
原因是,如果不支持
document.head
,则至少返回正确的值。至于速度测试,毫秒是很长的时间。我怀疑真的花了这么长时间。实际上,我为此做了一个
jsPerf
。它显示getElementsByTagName
函数的速度大约慢80%。关于javascript - document.head诉document.getElementsByTagName (“head”)[0],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16204756/