Search code examples
javascripthtmlhtml5-template

Where does the HTML spec state that a <template>'s contents are inert?


The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script. The "contents of the template" (as accessed via HTMLTemplateElement.prototype.content) are stored in a DocumentFragment associated with a different Document other than the main document.

So, because templ.content.ownerDocument != document, this is OK:

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

templ.content is an inert DocumentFragment, that's fine.


Edit: The rest of the question, below, has an incorrect premise -- I was testing this by creating a template in JavaScript with document.createElement instead of via HTML, which yields different results. More precisely, when creating a template and using document.body.appendChild, the template is adopted into document which 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.)


Solution

  • Well, there's this note on the template element description:

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

    (My emphasis.) It then goes into it in a fair bit of detail in the following paragraphs (my emphasis):

    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