问题
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