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

Viewed 822

Is there any consideration that should be done between using the head or the body to add template tags? Ex:

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

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

I just stumble upon a code base that dynamically adds templates to head and my gut tells me that maybe it isn't the best idea, but maybe it doesn't matter?

2 Answers

Templates are among the most flexible of all the elements in where they can be placed. 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." essentially means in the head.

"Where phrasing content is expected." essentially means anywhere the valid child of a body element can go.

"Where script-supporting elements are expected" means it can go even in places that phrasing content can't, such as the child of ul, ol, table, tbody, tr etc elements.

I think that it ought to be in the <body>. Mozilla defines the permitted content in the <head> tag to be:

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.

Looking at the example on MDN, they've added the <template> tag within the body as well.

Related