Search code examples
htmlmicrosoft-edgehtml5-template

HTML5 template tag does not work with edge?


I have made a website which uses the template-tag for some JavaScript functionality. And this functionality does not work in edge, and I asume that is because of the template-tag since I have heard in the past that their can be some problem between them.

But according to caniuse.com edge should have support for the template-tag, without any issues listed. Also according to MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template Edge should have had support since version 13. I have tested in version 20 ov Edge.

I also dont get any javascript errors in the edge consle, so I asuming it can only be a problem with the template-tag.

My question is rather simple. Does or does not Edge have support for the template-tag? Or is a work around need (shiv or similar)?


Solution

  • Yes, MS Edge absolutely does support templates. However, there is a known issue in retrieving the firstElementChild of a document fragment such as the content of a template. When utilizing a template, it's most common to grab the firstElementChild of the content, clone it, and place it somewhere in the DOM, so it may appear that templates are completely broken in MS Edge at first glance.

    At the time of this post, the following code will fail in MS Edge:

    var clone = template.content.firstElementChild.cloneNode(true);
    

    This code will work in MS Edge and all other post MS IE browsers:

    var clone = template.content.querySelector("*").cloneNode(true);
    

    Or better yet, you can even accommodate MS IE:

    var clone = template.content ? template.content.querySelector("*").cloneNode(true) : template.firstElementChild.cloneNode(true);
    

    In this last code snip-it, older browsers like MS IE will create the clone properly, but templates in markup will be parsed and displayed unless hidden. The template is usable, but it has none of the native performance benefits.