【发布时间】:2018-04-28 20:51:17
【问题描述】:
tl;dr:试图将 <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/">
这不会引发任何错误,但 <template> 对我的页面不可见,并且我收到以下错误:
未捕获的类型错误:无法读取 null 的属性“内容” 在 web-component2.html:31
因为var template = document.querySelector('template'); 返回null。
什么给了?如何访问我的模板?
附:
使用这个page as a guide
从here得到html导入语句
编辑:
我看到一个请求发送到我的站点并返回 304,这是响应:
<html>
<head>
<template>
<style>div{ background-color: red;}</style>
<div id = "testTemplate">1</div>
</template>
</head>
<body>
</body>
</html>
所以我希望 html 可以正常返回(但无法从我的本地页面访问) - 我不确定是否需要隔离 <template> 或缺少同样简单的东西。
【问题讨论】:
-
您是否查看过模板的 HTTP 请求是什么样的?使用浏览器的“网络”开发者工具。
-
@Pointy 状态码:304,我看到我的 html 回来了。谢谢,我不知道为什么我没有在最初的帖子中包含这些信息。所以,看起来我可以从远程获取我的 html...但无法从我的本地 html 中看到它。
-
您是否已阅读有关
<link rel=import>的博客文章到有关“使用内容”的部分? -
@Pointy:不,直到你指出来,我只是做了假设——请原谅我和 ty 的帮助:
var contentFromRemote = document.querySelector('link[rel="import"]').import;和template = contentFromRemote.querySelector('template');做到了。
标签: javascript html templates web-component