将模板标签添加到 HTML 文档的头部或正文之间有什么区别吗?

Is there any difference between adding template tags to the head or body of an HTML doc?

使用head还是body添加模板标签有什么需要注意的地方吗?例如:

conste template = document.createElement('template');
// add template content etc.

document.body.appendChild(template);
// or
document.head.appendChild(template);

我偶然发现了一个动态添加模板到 head 的代码库,我的直觉告诉我这可能不是最好的主意,但也许没关系?

我觉得应该在<body>Mozilla定义<head>标签中的允许内容为:

If the document is an <iframe> srcdoc document, or if title information is available from a higher level protocol, zero or more elements of metadata content. Otherwise, one or more elements of metadata content where exactly one is a <title> element.

查看 MDN 上的示例,他们也在正文中添加了 <template> 标签。

模板是可以放置它们的所有元素中最灵活的元素之一。 The spec says

Contexts in which this element can be used:
- Where metadata content is expected.
- Where phrasing content is expected.
- Where script-supporting elements are expected.
- As a child of a colgroup element that doesn’t have a span attribute.

"Where metadata content is expected."本质上是在脑袋里的意思。

"Where phrasing content is expected." 本质上意味着 body 元素的有效子元素可以去的任何地方。

"Where script-supporting elements are expected" 表示它甚至可以出现在短语内容不能出现的地方,例如 ul、ol、table、tbody、tr 等元素的子元素。