Unfortunately, the template tag is not allowed to contain <html>
tags. per 4.1.1 of the HTML specification:
Contexts in which [the <html>
] element can be used:
- As document's document element.
- Wherever a subdocument fragment is allowed in a compound document.
and from 4.12.3, the <template>
tag does not provide either of these contexts. For the same reason, you can't use <head>
, <body>
or <title>
tags either. Chrome and Firefox both actively strip out the invalid tags from the <template>
, preventing you from using it.
The best way of storing HTML for use in iframes is to put the HTML code in a different file in your web server.
However, an acceptable alternative is to store the HTML inside your <iframe>
, then populating the srcdoc attribute with the content.
<iframe id="yourIframe">
<!-- Everything inside here is interpreted as text, meaning you can even put doctypes here. This is legal, per 12.2.6.4.7 and 4.8.5 of the HTML specification. -->
<!doctype html>
<html>
<head>
<title>Document</title>
</head>
<body>
<main>Content</main>
</body>
</html>
</iframe>
...
<script>
...
const iframe = document.getElementById("yourIframe");
iframe.srcdoc = iframe.innerHTML;
</script>