如何测试浏览器是否支持特定的 JavaScript 代码行

How test if a particular line of JavaScript code is supported by Browser

本文关键字:JavaScript 代码 支持 是否 何测试 测试 浏览器      更新时间:2023-09-26

有人可以建议如何测试浏览器是否支持特定的JavaScript代码行。如果不是,我该如何处理?当我正在学习JavaScript时,这将是一个很大的帮助。

这似乎是使用 try/catch 的最佳时机:

    try {
        // your JavaScript here
        document.executeSomeUnknownFunction();
    }
    catch (error) {
        console.log("There was an error: " + error);
    }
console.log("...but nothing broke");

或者,假设它是您要测试的对象的方法(例如querySelectorAll()):

if ('querySelectorAll' in document) {
  console.log("We support  'document.querySelectorAll()'");
 }

引用:

  • in运算符。
  • try...catch .

您可以: 1) 假设代码有效,并处理它不起作用的情况:

try{
   // ...
}catch(e){
   // an error occurred
}

或者 2) 检查它所依赖的函数是否存在,然后使用它:

if(window.yourfunction){
   // The function is present in the global scope
}else{
   // Not available, try alternatives?
}