我可以在浏览器中检测到async / await吗?
问题描述:
作为标题,如何在浏览器中检测async / await es7支持?
As title, how can I detect async/await es7 support in browser?
这可能吗?
答
与任何其他语法特征一样,应对其进行评估以便进行检测。由于可以限制 eval
,因此在启用CSP时可能无法实现此目的:
As any other syntactic feature, it should be evaluated in order to be detected. Since eval
can be restricted, this may be impossible when CSP is enabled:
let isAsync = true;
try {
eval('async () => {}');
} catch (e) {
if (e instanceof SyntaxError)
isAsync = false;
else
throw e; // throws CSP error
}
如果目标浏览器有可能不支持一个功能,代码应该被转换。
If there's a chance that target browsers don't support a feature, the code should be transpiled.
允许避免对 eval
的CSP限制的替代方法是使用用于检测语法功能的外部脚本,如此处所述。
The alternative that allows to avoid CSP restrictions on eval
is to use external script to detect syntactic features, as described here.