document.head v. document.getElementsByTagName(“head”)[0]

后端 未结 4 2040
遇见更好的自我
遇见更好的自我 2021-02-02 14:56

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

4条回答
  •  一个人的身影
    2021-02-02 15:48

    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.

    So for

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

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

    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.

提交回复
热议问题