我想存储整个HTML文档,以便稍后放入iframe(srcdoc(。
我可以像这样将所有内容放入模板中,包括 html、头部和身体吗?
<template>
<html>
<head>
<title>Document</title>
</head>
<body>
<main>Content</main>
</body>
</html>
</template>
如果没有,存储整个文档的最佳方法是什么?谢谢!
遗憾的是,模板标签不允许包含<html>
标签。 根据 HTML 规范的 4.1.1
可以使用 [
<html>
] 元素的上下文:
- 作为文档的文档元素。
- 复合文档中允许子文档片段的任何位置。
从 4.12.3 开始,<template>
标记不提供这些上下文中的任何一个。出于同样的原因,您也不能使用 <head>
、 <body>
或 <title>
标签。Chrome和Firefox都会主动从<template>
中删除无效标签,阻止您使用它。
存储 HTML 以在 iframe 中使用的最佳方法是将 HTML 代码放在 Web 服务器的不同文件中。
但是,一个可接受的替代方法是将 HTML 存储在您的<iframe>
中,然后用内容填充 srcdoc 属性。
<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>