如何识别检测rel ="预取"

时间:2017-02-02 13:49:55

标签: javascript html5

根据caniuse.com资源 prefteching <link rel="prefetch" href="some-resource" />仅适用于某些浏览器。

如何在JavaScript中检测此功能?在下面的示例中,如何获得isPrefecthSupported

的值
if(isPrefecthSupported) {
    let link = document.createElement('link');
    link.setAttribute('rel', 'prefetch');
    link.setAttribute('href', url);
    link.setAttribute('disabled', true);
    document.querySelector('head').appendChild(link);
} else {
   //try something else...
}

1 个答案:

答案 0 :(得分:0)

我终于设法检测它了。有边缘情况(不支持DomTokenList.supports时),但你可以这样做:

 
var support = function support(feature){
    var tokenList;
    var fakeLink = document.createElement('link');
    try {
        if(fakeLink.relList && _.isFunction(fakeLink.relList.supports)){
            return  fakeLink.relList.supports(feature);
        }
    } catch(err){
        return false;
    }
};
var isPrefetchSupported = support('prefetch');
var isPreloadSupported = support('preload');