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>
当我运行上面的代码时,我的模板就会显示。伟大的。现在我正在尝试将我的网络组件移动到其他地方托管的网站。所以我创建了一个 github 页面并确认其有效:https://myusername.github.io/webcomponent/
.
这是一个完整的 html 页面,头部有我的模板(与上面相同)。然后,我尝试使用以下方法将 html 从 github 页面拉入我的 html 中:
<link rel="import" href="https://myusername.github.io/webcomponent/">
这不会引发任何错误,但 <template>
在我的页面上不可见,并且出现以下错误:
Uncaught TypeError: Cannot read property 'content' of null at web-component2.html:31
因为var template = document.querySelector('template');
返回null
.
什么给了?如何访问我的模板?
附注
使用这个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>
或者我错过了同样简单的东西。
最佳答案
万一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>
元素有一个“导入”属性,用作已导入文档的根目录,然后您可以使用 querySelector()
(大概还有其他 document
风格的 API)来挖掘并在导入的内容中查找内容。
关于javascript - 从另一个网站导入 <template> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310641/