如何在JS中对三等号运算符和Promise支持进行功能检查? [英] How to feature-check for three-equals-signs operator and promises support in JS?

查看:235
本文介绍了如何在JS中对三等号运算符和Promise支持进行功能检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写脚本,我想将其分为几个模块。 基准模块将支持较旧的浏览器,而这些浏览器不支持===和promises等新语法。

I'm writing scripts which I want to split into several modules. The "baseline" modules will support older browsers, which do not support new syntax such as === and promises.

如果浏览器将加载高级模块通过功能检查。

The "advanced" modules will be loaded if the browser passes a feature-check.

我的问题是,如何检查浏览器是否支持 === 运算符,并且 .then(function(){})承诺没有先实际使用语法而在较旧的浏览器中引起语法错误吗?

My question is, how do I check if browser supports === operator and .then(function(){}) promise syntax without actually using them first, and causing a syntax error in older browsers?

if (/*what goes here*/) {
    var script = document.createElement('script');
    script.src = '/advanced.js';
    script.async = false;
    document.head.appendChild(script);
}


推荐答案

如果浏览器支持promises,它将支持然后。一种查看浏览器是否支持诺言(不抛出错误)的方法(以及其他)是查看是否 window.Promise 存在:

If a browser supports promises, it will support then. One way (among others) to see if a browser supports promises (without throwing an error) would be to see if window.Promise exists:

if(window.hasOwnProperty("Promise"))
{
  console.log("Promises are supported.");
}
else
{
  console.log("This browser does NOT support promises.");
}

对于 === 不必担心您会担心这一点。 === 已于12月的第三版中添加到ECMAscript中。 1999年,很难想象今天会有任何人(甚至是顽固的落后者)使用不支持它的浏览器。

As for ===, I don't think you'll have to worry about that one. === was added to ECMAscript in the 3rd edition in December of 1999 and it is hard to imagine anyone (even a diehard laggard) using a browser today that doesn't support it.

更新:

如果您真的坚持要检测 === 支持,我的结论(来自下面的评论)就是要做到这一点通过研究哪些浏览器不支持 === 并使用浏览器检测来检测那些浏览器。希望其他人能为您提供我没有想到的简便方法。

If you really insist on detecting === support, my conclusion (from my comments below) is to accomplish this by researching which browsers do not support === and using Browser Detection to detect those browsers. I hope someone else offers you an easier way I'm not thinking of.

这篇关于如何在JS中对三等号运算符和Promise支持进行功能检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆