tl;医生:试图
<template>
元素托管在其他地方,怎么办?
我有一个
html
<head>
(重点是它是一个
template
标签):
<template>
<style>div{ background-color: red;}</style>
<div id = "testTemplate">1</div>
</template>
正如所料,在我将模板附加到某个阴影根之前,此代码不会生成模板,例如:
<script>
var template = document.querySelector('template');
var containerHost = document.querySelector('.containerHost');
var shadowRoot = containerHost.createShadowRoot();
shadowRoot.appendChild(document.importNode(template.content, true));
</script>
当我运行上面的代码时,会显示我的模板。太棒了现在,我正在尝试将我的web组件移动到其他地方托管的网站。所以我创建了一个github页面,我确认了它的效果:
https://myusername.github.io/webcomponent/
.
这是一个完整的html页面,其中包含我的模板(同上)。然后,我尝试使用以下方法将html从github页面拉入html:
<link rel="import" href="https://myusername.github.io/webcomponent/">
这不会抛出错误,但
<模板(>);
对我的页面不可见,我收到以下错误:
未捕获的TypeError:无法读取null的属性“content”
在web-component2。html:31
因为
var template = document.querySelector('template');
退货
null
.
有什么好处?如何获取模板?
附笔。
使用此
page as a guide
从中获取html导入语句
here
编辑:
我看到一个请求正在发送到我的站点,并返回一个
304
,这是回应:
<html>
<head>
<template>
<style>div{ background-color: red;}</style>
<div id = "testTemplate">1</div>
</template>
</head>
<body>
</body>
</html>
所以
html
<
或者我错过了同样简单的事情。