javascript - HTML 规范在哪里声明 <template> 的内容是惰性的?

标签 javascript html html5-template

The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.template 的内容”(通过 HTMLTemplateElement.prototype.content 访问)存储在 DocumentFragment 中与不同的Document相关联除主要document .

所以,因为templ.content.ownerDocument != document ,这样就可以了:

<template id="templ">
  <script>console.error('This does not execute!');</script>
</template>

templ.content是惰性的 DocumentFragment ,没关系。

<小时/>

编辑:下面的问题的其余部分有一个不正确的前提 - 我正在通过使用 document.createElement 在 JavaScript 中创建模板来测试这一点。而不是通过 HTML,这会产生不同的结果。 更准确地说,在创建模板并使用 document.body.appendChild 时,模板被采纳为 document其中specifically adopts template.content into document .

However, the template itself, and its descendants, are associated with document:

templ.children[0].tagName == 'script'
templ.children[0].ownerDocument == document

In other words, the script is still a part of the main Document, which would normally mean it executes.

While the spec explains the DocumentFragment accessed via .content, that doesn't account for this concrete, instantiated <script> instance having its associated Document be the main document but not executing.

Does the spec explain somewhere exactly why this <script> isn't executed? How is it excluded from execution if it does belong to document?


(I realize it's useful for the script not to execute. This is a question about the spec, not about the usefulness of <template> or whether the in-browser behavior is appropriate.)

最佳答案

嗯,有this note关于 template 元素描述:

Note: Templates provide a method for declaring inert DOM subtrees and manipulating them to instantiate document fragments with identical contents.

(我的重点。)然后在下面的段落中详细介绍它(我的重点):

A Document doc's appropriate template contents owner document is the Document returned by the following algorithm:

  1. If doc is not a Document created by this algorithm, run these substeps:

    1. If doc does not yet have an associated inert template document then run these substeps:

      1. Let new doc be a new Document (that does not have a browsing context). This is "a Document created by this algorithm" for the purposes of the step above.

      2. If doc is an HTML document, mark new doc as an HTML document also.

      3. Let doc's associated inert template document be new doc.

    2. Set doc to doc's associated inert template document.

  2. Return doc

关于javascript - HTML 规范在哪里声明 <template> 的内容是惰性的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34457979/

相关文章:

javascript - javascript中的日期比较

javascript - 当转到另一个 chrome 选项卡时,setInterval 计时器会更慢

javascript - 获取正在翻译的元素的位置

javascript - Meteor 和 Handlebars #each 迭代对象

javascript - 使用多个下拉列表选择的 URL 查询字符串(最好是 PHP?)

html - 将链接限制为适当的文本

jquery - 如何在HTML 5中为音频,视频,CSS,图像创建预加载器?

angular - 在 Angular2 中使用纸质数据表

javascript - HTML 导入不起作用...即使它受支持