HTML <template> 在边缘

HTML <template> on Edge

我需要决定是使用 <template> 还是使用 documentFragment 在 Javascript 中构建一个高度嵌套的元素。使用 <template> 会干净很多,但 Edge 支持很关键,caniuse.com 似乎表明只有部分支持:

https://caniuse.com/#feat=template

  1. Does not support Document.importNode on templates, nested templates or elements that contain templates.

  2. Does not support Node.cloneNode on templates, nested templates or elements that contain templates.

问题是我无法使用 Edge 进行测试(不是 运行 Windows 10 也无法访问浏览器测试套件)而且我也找不到任何东西在 MDN 或 Microsoft 文档中在线了解它。无法将模板克隆到文档中几乎意味着使用 <template> 的标准方式超出了 window,这对我来说没有意义,因为这似乎是 <template>.

唯一声称这是 caniuse.com 的地方,但我已经学会相信它,这让我不确定要使用哪种方法。为了安全起见,我很可能只使用 documentFragment,但我想知道这是否是 caniuse.com 上的错误,或者是否有另一种使用 <template> 的明智方法是显而易见的我想念它。

以下测试文档证明 importNodecloneNode 似乎可以在 Edge 中与 template 一起正常工作,至少对于版本 15 及更高版本。

<!DOCTYPE html>

<title>&lt;template&gt; testing</title>

<div id="wrapper">
    <template id="outer">lol<template id="inner">wut</template></template>
</div>

<script>
    var wrapper = document.getElementById('wrapper').cloneNode(true);
    var outer = wrapper.querySelector('#outer');
    var clone = outer.cloneNode(true);
    var inner = document.importNode(clone.content.lastChild, true);
    var content = document.importNode(inner.content, true);
    document.body.appendChild(content);
</script>

就其价值而言,您通常不会像问题中提到的那样 "clone the template into the document",而是将模板的 内容 克隆到文档中:

let template = document.querySelector('template');
document.body.append(document.importNode(template.content, true));