How to feature-check for three-equals-signs operator and promises support in JS?

泪湿孤枕 提交于 2020-01-25 06:42:27

问题


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.

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);
}

回答1:


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.");
}

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.

UPDATE:

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.



来源:https://stackoverflow.com/questions/59813590/how-to-feature-check-for-three-equals-signs-operator-and-promises-support-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!