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

1

7

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?

Feather answered 20/9, 2018 at 21:36 Comment(1)
I think you can only add stuff like script and link tags to the head, not html elements. #1901374Gotthelf
W
7

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.

Weathercock answered 20/9, 2018 at 22:22 Comment(1)
Nice, then per WHATWG, I can have templates as list-items and table-cells (if they are to populate their respective parents anyway).Patton

© 2022 - 2024 — McMap. All rights reserved.