`` Template Syntax - Graceful Degredation

前端 未结 2 1558
面向向阳花
面向向阳花 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 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("`
    `".....); } catch(e) { if(e instanceof SyntaxError) { template = '
    ' + ... } }

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

提交回复
热议问题