Search code examples
javascripthtmlperformanceunderscore.js-templatinghtml5-template

Avoid cloning HTMLTemplate to retrieve innerHTML?


I have all templates in <template> tags to improve runtime performance (avoids rendering), but I am wondering if I am using them correctly when I need their contents for compiling my Underscore templates. What I want is the string content of the DOM element, but I seem unable to access it without cloning it from the shadow DOM. I am doing this:

function compileTemplate(templateId){
    var el = document.getElementById(templateId);
    var templateMarkup = _.unescape(el.cloneNode(true).innerHTML);
    return compiledTemplate = _.template(templateMarkup);
}

This works, but is there a more efficient that avoids cloning?


Solution

  • You should be able to get the innerHTML string directly without cloning:

    function compileTemplate(templateId) {
        var el = document.getElementById(templateId);
        var templateMarkup = _.unescape(el.innerHTML);
        return compiledTemplate = _.template(templateMarkup);
    }
    

    function compileTemplate(templateId) {
        var el = document.getElementById(templateId);
        console.log( el.innerHTML )
    }
    
    function test() {
        compileTemplate('T1')
    }
    <template id=T1>
      HTML inside
    </template>
    
    <button onclick=test()>Compile</button>