【问题标题】:Import <template> Element From Another Website从另一个网站导入 <template> 元素
【发布时间】:2018-04-28 20:51:17
【问题描述】:

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


我在本地有一个html 页面,它在&lt;head&gt; 中有以下模板(关键是它是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/">

这不会引发任何错误,但 &lt;template&gt; 对我的页面不可见,并且我收到以下错误:

未捕获的类型错误:无法读取 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 可以正常返回(但无法从我的本地页面访问) - 我不确定是否需要隔离 &lt;template&gt; 或缺少同样简单的东西。

【问题讨论】:

  • 您是否查看过模板的 HTTP 请求是什么样的?使用浏览器的“网络”开发者工具。
  • @Pointy 状态码:304,我看到我的 html 回来了。谢谢,我不知道为什么我没有在最初的帖子中包含这些信息。所以,看起来我可以从远程获取我的 html...但无法从我的本地 html 中看到它。
  • 您是否已阅读有关 &lt;link rel=import&gt; 的博客文章到有关“使用内容”的部分?
  • @Pointy:不,直到你指出来,我只是做了假设——请原谅我和 ty 的帮助:var contentFromRemote = document.querySelector('link[rel="import"]').import;template = contentFromRemote.querySelector('template'); 做到了。

标签: javascript html templates web-component


【解决方案1】:

如果关于导入的the linked article 消失了:获取导入的内容后,您必须从&lt;link&gt; 元素中获取内容,而不是从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)">

例如。 &lt;link&gt; 元素有一个“import”属性,用作已导入文档的根,然后您可以使用 querySelector()(可能还有其他 document 样式的 API)来挖掘并找到原来的内容进口的。

【讨论】:

    【解决方案2】:

    无法从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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多