为一个Javascript特征创建特征检测(intersectionObserver)

时间:2018-02-14 18:05:28

标签: javascript feature-detection intersection-observer

有没有办法在变量中存储内置的javascript方法,以便在某些浏览器中无法使用此方法时设置不同的行为?

我的具体情况是针对在Safari或旧版MS浏览器中无法使用的intersectionObserver。我有一些由此引发的动画,并且如果intersectionObserver不可用则想关闭它们。

基本上我想要做的是:

var iO = intersectionObserver;

if ( !iO ) {
 // set other defaults
}

我真的不想只为一个功能加载polyfill或库吗?

非常感谢

艾米丽

1 个答案:

答案 0 :(得分:4)

运算符中的 广泛用于检测浏览器支持的功能。 JavaScript功能作为window对象的属性全局可用。因此,我们可以检查window元素是否具有该属性。

if("IntersectionObserver" in window){
    /* work with IntersectionObserver */
}
if("FileReader" in window){
    /* work with FileReader */
}
  

如果指定的属性位于in运算符中,则true运算符返回boolean   指定对象或其原​​型链   对象中的语法: prop    [来源:developer.mozilla.org]

因此,您也可以将结果保存在var iO = "IntersectionObserver" in window; /* true if supported */ if ( !iO ) { // set other defaults } 变量中,稍后在代码中使用。

$result = [];
$dom=new DOMDocument;
libxml_use_internal_errors(true);  // do not display warnings on erroneous lines
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate("//meta[(@name or @http-equiv) and @content]") as $node) {  // target <meta> tags containing both a name & content attribute
    if ($value = $node->getAttribute('name')) {
        $attr = 'name';
    } else {
        $attr = 'http-equiv';
        $value = $node->getAttribute('http-equiv'); 
    }
    $result[]=[$attr => $value, 'content' => $node->getAttribute('content')];
}

var_export($result);