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 withdocument
:templ.children[0].tagName == 'script' templ.children[0].ownerDocument == document
In other words, the
script
is still a part of the mainDocument
, 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 associatedDocument
be the maindocument
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 todocument
?
(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.)
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:
If doc is not a Document created by this algorithm, run these substeps:
If doc does not yet have an associated inert template document then run these substeps:
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.
If doc is an HTML document, mark new doc as an HTML document also.
Let doc's associated inert template document be new doc.
Set doc to doc's associated inert template document.
Return doc