`` Template Syntax - Graceful Degredation

前端 未结 2 1557
面向向阳花
面向向阳花 2021-01-24 00:06

The new javascript template syntax is great. Super readable and powerful. I\'d like to start using it.

I tried this template:

function addGalleryItem(ima         


        
相关标签:
2条回答
  • 2021-01-24 00:52

    You can't use try...catch statement to catch syntax errors, because they are thrown even before the code is executed.

    You either have to drop support for browsers which doesn't support template literals or use Babel.

    0 讨论(0)
  • 2021-01-24 01:02

    Generally you can use eval to assert if the browser supports certain syntax changes:

    var isTemplateSupported = true;
    try {
        eval("``");
    }
    catch(e) {
        isTemplateSupported = false;
    }
    console.log("Supports Template Literals", isTemplateSupported);
    

    So for your implementation:

    var template;
    try {
        template = eval("`<section class=\"imageGalleryItem\">`".....);
    }
    catch(e) {
        if(e instanceof SyntaxError) {
            template = '<section class="imageGalleryItem">' + ...
        }
    }
    

    But it's much easier to use a transpiler because it would be tedious to support two implementations every time you need a literal.

    0 讨论(0)
提交回复
热议问题