在浏览器中检测模板文字(在异常情况下)

时间:2019-04-09 00:40:15

标签: javascript feature-detection template-literals

我有一些使用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的重复,这是一个非常不同的上下文中类似的听起来的问题。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

您可能有一个带有简单模板文字的<script>标记,该文字初始化了一些全局符号,然后检查单独 <script>是否存在该全局符号。 / p>

如果第一个<script>出现语法错误(因为JavaScript运行时很旧),则它将不会运行。然后,第二个<script>会知道模板文字是否起作用。

但是-这并不能真正为您带来很多好处,因为如果它们不起作用,那么使用模板文字导入的任何其他代码都会也失败了可能最好的办法是根据上述测试有条件地导入好的代码或解决方法代码。