Javascript 进口<;模板>;来自其他网站的元素

Javascript 进口<;模板>;来自其他网站的元素,javascript,html,templates,web-component,Javascript,Html,Templates,Web Component,tl;dr:试图在其他地方托管元素,怎么办? 我在本地有一个html页面,在中有以下模板(重点是它是模板标记中的一些内容): 这不会引发任何错误,但对我的页面不可见,我会遇到以下错误: 未捕获的TypeError:无法读取null的属性“content” 网址:web-component2.html:31 因为var template=document.querySelector('template')返回null 有什么好处?如何获取模板 附言。 使用此 从中获取html导入语句 编辑:

tl;dr:试图在其他地方托管
元素,怎么办?


我在本地有一个
html
页面,在
中有以下模板(重点是它是
模板
标记中的一些内容):

这不会引发任何错误,但
对我的页面不可见,我会遇到以下错误:

未捕获的TypeError:无法读取null的属性“content” 网址:web-component2.html:31

因为
var template=document.querySelector('template')返回
null

有什么好处?如何获取模板

附言。 使用此
从中获取html导入语句


编辑:

我看到一个请求转到我的站点,然后返回一个
304
,以下是响应:

<html>
<head>

  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>

</head>
<body>
</body>
</html>

div{背景色:红色;}
1.
因此,我期望的
html
会很好地返回(但无法从我的本地页面访问)-我不确定是否需要隔离
,或者我遗漏了同样简单的内容。

如果关于导入的内容消失了:一旦获取了导入的内容,您必须从
元素中获取内容,不是来自
文档

function getTemplate(e) {
  let template = e.target.import.querySelector("template");
  shadowRoot.appendChild(document.importNode(template.content, true));
}
...

<link rel=import href="http://what.ever" onload="getTemplate(event)">
函数getTemplate(e){ 让template=e.target.import.querySelector(“模板”); appendChild(document.importNode(template.content,true)); } ...

比如说。
元素有一个“import”属性,该属性作为已导入文档的根,然后您可以使用
querySelector()
(可能还有其他
文档
样式的API)在导入的内容中查找内容。

无法从
文档
DOM访问导入的模板。您需要获取脚本运行的当前文档,并从中选择模板。比如说,

const currentDocument = document.currentScript.ownerDocument;
// Above is the document in which the script is executing. 
// Template also resides in this document.
const template = currentDocument.querySelector('#my-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);

也要重新考虑使用HTML导入,因为它们一直都在使用。考虑使用Ajax请求获取HTML。您可以找到一个示例。

您研究过模板的HTTP请求是什么样子的吗?使用浏览器的“网络”开发工具。@Pointy状态代码:304,我看到我的html回来了。谢谢,我不知道为什么我没有在最初的帖子中包含这些信息。所以,看起来我可以从远程获取我的html…但无法从本地html中看到它。你读过关于
的博客文章到关于“使用内容”的部分了吗?@Pointy:没有,直到你指出,我才做了假设-请原谅我和ty的帮助:
var contentFromRemote=document.querySelector('link[rel]=“导入”]')。导入;
template=contentFromRemote.querySelector('template');
执行此操作。
<html>
<head>

  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>

</head>
<body>
</body>
</html>
function getTemplate(e) {
  let template = e.target.import.querySelector("template");
  shadowRoot.appendChild(document.importNode(template.content, true));
}
...

<link rel=import href="http://what.ever" onload="getTemplate(event)">
const currentDocument = document.currentScript.ownerDocument;
// Above is the document in which the script is executing. 
// Template also resides in this document.
const template = currentDocument.querySelector('#my-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);