检查浏览器是否支持`.textContent`的最佳方法?

Ori*_*iol 3 javascript performance dom browser-feature-detection

我想检查浏览器是否支持 .textContent

我想过这些选择:

  1. if( document.body.textContent ) { }
  2. if( document.createElement('div').textContent !== void(0) ) { }

当然,第一个更简单,但我看到的问题是浏览器可能计算所有字符串,如果网站很大,这可能会很慢.

然后,我应该选择哪一个?或者有更好的选择吗?

编辑:我创建了一个jsperf

rai*_*7ow 6

随着...

'textContent' in document.body
Run Code Online (Sandbox Code Playgroud)

...表达式您只需检查对象中的属性(textContent)是否存在document.body,而不实际检查其值.

是的,它false在IE8中.

  • @Oriol [更新jsperf](http://jsperf.com/checking-textcontent-browser-support/2)使用`document.body.hasOwnProperty('textContent')`表明它在Firefox和Chrome中速度最快.比IE10略慢于`in`. (2认同)