从另一个网站导入<template>元素

时间:2017-11-15 14:59:34

标签: javascript html templates web-component

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页面,其中包含我的模板(与上面相同)。然后我尝试使用以下命令将github页面中的html拉入我的html:

  <link rel="import" href="https://myusername.github.io/webcomponent/">

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

  

未捕获的TypeError:无法读取属性&#39;内容&#39;为null       在web-component2.html:31

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

是什么给出的?我如何进入我的模板?

P.S。 使用此page as a guide
here

获得了html import语句

编辑:

我看到一个请求发送到我的网站并返回304,这是回复:

<html>
<head>

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

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

所以我期待html恢复正常(但无法从我的本地页面访问) - 我不确定是否需要隔离<template>或遗漏的内容同样简单。

2 个答案:

答案 0 :(得分:2)

如果有关导入的the linked article消失:获取导入的内容后,您必须从<link>元素中获取内容,而不是从document获取内容:

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)">
例如,

<link>元素具有“import”属性,该属性用作已导入文档的根,然后您可以使用querySelector()(可能还有其他document样式API)来挖掘并在导入的内容中查找内容。

答案 1 :(得分:0)

无法从document 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导入,因为它们已经deprecated and are likely to be removed from the spec。考虑使用AJAX请求获取HTML。您可以找到示例here

相关问题