我想使用polyfill进行可选链接,但我不想为已经支持此功能的浏览器提供polyfill。
有没有办法确定浏览器是否支持可选链?
这有效:
const isOptionalChainingSupported = () => {
try {
eval('const foo = {}; foo?.bar');
} catch {
return false;
}
return true;
}
我在网上找不到任何解决方案。我设法想出了这个:
const getIsOptionalChainingSupported = () => {
try {
const test = {};
const isUndefined = test?.foo?.bar
if (isUndefined === undefined) {
return true
}
} catch {
return false
}
}
对我有用的唯一解决方案是在标头中添加脚本标记,然后保护全局变量
<script>
let a = {};
a?.a?.a;
var supportsOpChaining = true;
</script>
然后
if (typeof supportsOpChaining !== "undefined"){
// The code that uses optional chaining
}
else {
// The code that not using optional chaining
}
(我将“unsafe-eval”添加到我的网站标题中,因此我无法使用 eval)