【问题标题】:Detecting Template Literals in the Browser (in an unusual context)在浏览器中检测模板文字(在不寻常的上下文中)
【发布时间】:2019-08-30 04:51:26
【问题描述】:

我有一些使用 ES6 模板字面量的 JS,我想确保它们可以回退到旧版浏览器。

通常要检测 javascript 功能,我会执行标准 if 语句来查看是否在窗口对象中检测到该功能:

if("JavascriptFeature" in window){
    // do something with the feature
}

我将如何在下面的上下文中使用模板文字来做到这一点?

我有下面的代码,它基本上用于确保 100vh 属性在移动/iPad 上按需要工作,我想将 JS 包装成一个条件,只有在浏览器可以使用模板文字时才会触发:

JS

function resizeSection(){
    // First we get the viewport height and we multiple it by 1% to get a value for a vh unit

    var vh = window.innerHeight * 0.01;

    // Then we set the value in the --vh custom property to the root of the document

    document.documentElement.style.setProperty('--vh', `${vh}px`);
}

resizeSection();
addEventListener("resize", resizeSection, false)

CSS

.heading-section {
    /* Use vh as a fallback for browsers that do not support Custom Properties */
    height: calc(100vh); 

    /*MODERN BROWSERS*/
    height: calc(var(--vh, 1vh) * 100);
}

请注意:这不是 Detecting template literals in javascript 的重复,这是一个在非常不同的上下文中听起来相似的问题。

【问题讨论】:

  • 如果浏览器 JavaScript 环境不理解模板文字语法,您的代码将根本没有机会运行,因为它会因语法错误而失败。

标签: javascript feature-detection template-literals


【解决方案1】:

应在eval 语句中检查语法特征。

例如,检查字符串文字看起来像

function supportsLiterals() {
  try{ return eval("''===``") }
  catch(e){ return false; }
}

console.log(supportsLiterals());

现在,你必须明白知道这对你的代码没有什么好处:你将无法在代码中的任何地方使用这种语法,不支持的浏览器将执行 (当然会有办法,但太糟糕了,你甚至不应该考虑它

因此,只有当您有两个版本的代码并且您能够动态加载它们时,这才是有益的。

相反,最好使用最新功能编写代码,然后转译您的代码,以便每个人都可以使用它。

例如,使用 online version of Babel 您的代码将转译为

function resizeSection() {
  // First we get the viewport height and we multiple it by 1% to get a value for a vh unit
  var vh = window.innerHeight * 0.01; // Then we set the value in the --vh custom property to the root of the document

  document.documentElement.style.setProperty('--vh', "".concat(vh, "px"));
}

resizeSection();
addEventListener("resize", resizeSection, false);

【讨论】:

    【解决方案2】:

    语法检查发生在任何代码运行之前。不支持新语法的运行时根本不会运行任何脚本;在解析时间之后,您无法“保护”脚本的某些部分,因为为时已晚。

    你可以有一个<script>标签和一个简单的模板文字来初始化一些全局符号,然后检查一个单独的<script>这个全局符号是否存在。

    如果第一个 <script> 有语法错误(因为 JavaScript 运行时旧),那么它将不会运行。然后第二个<script> 将知道模板文字是否有效。

    然而——这对你没有多大好处,因为如果它们工作,那么你用模板文字导入的任何进一步的代码都会也失败了。可能您能做的最好的事情就是根据上述测试有条件地导入好的代码或变通方法代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2019-03-19
      • 2019-07-30
      • 2020-07-18
      相关资源
      最近更新 更多