creating an error message if browser does not support ES6 Template Literals

久未见 提交于 2019-12-01 12:50:11

问题


I have been using string literals in my javascript. I would like an error message to be shown if string literals are not supported. caniuse

My Idea was that i would create a function to see if the browser would correctly parse a string interpolated string

    var supportsStringInterpulation = false;
try {
    var stringInsert = 'is a';
    var stringTestExpected = "this " + stringInsert + " test";
    var stringTestAccual = `this ${stringInsert} test`;
    supportsStringInterpolation  = stringTestAccual === stringTestExpected;
}
catch (err) { console.error("failed to render ` ")}

if it is right do nothing

if wrong then the browser does not support then create and give error message.

My problem now is when I debug in IE 11 my expected behavior is that it would fail test and send supportsStringInterpulation = false further down to my code but it appears to break and stop processing that script.

Question 1

Is there a way to return a bool value to the question "Does the current Browser support ES6 Template Literals ?


回答1:


Yes. This is one of the legitimate uses of eval:

var supportsTemplateLiterals = false;
try {
    eval("`foo`");
    supportsTemplateLiterals = true;
}
catch (e) {
}
console.log("Supports template literals? " + supportsTemplateLiterals);

It works because the main code parses on a pre-ES2015 JavaScript engine, but the code in the eval doesn't; parsing chokes on the template literal.

On Chrome, Firefox, Edge, etc, that shows

Supports template literals? true

On IE (any version), it shows:

Supports template literals? false


来源:https://stackoverflow.com/questions/48408863/creating-an-error-message-if-browser-does-not-support-es6-template-literals

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