在浏览器中检测模板文字(在不寻常的上下文中)

问题描述 投票:0回答:2

我有一些使用ES6模板文字的JS,我想确保它有旧版浏览器的后备。

通常,为了检测javascript功能,我会使用标准if语句来查看是否在window对象中检测到该功能:

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 feature-detection template-literals
2个回答
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);

0
投票

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

您可以使用带有简单模板文字的<script>标记来初始化某个全局符号,然后检查单独的<script>是否存在该全局符号。

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

但是 - 这并没有给你带来太大的好处,因为如果它们不起作用,那么你用模板文字导入的任何其他代码也将失败。您可以做的最好的事情是根据上述测试有条件地导入好的代码或变通方法代码。

© www.soinside.com 2019 - 2024. All rights reserved.