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的属性"content"网址:web-component2.html:31
因为var template = document.querySelector('template');
返回null
。
什么东西?如何获取模板?
第页。S使用此页面作为指南
从这里获得html导入语句
编辑:
我看到一个请求发送到我的网站,然后返回304
,这是响应:
<html>
<head>
<template>
<style>div{ background-color: red;}</style>
<div id = "testTemplate">1</div>
</template>
</head>
<body>
</body>
</html>
因此,我期望的html
恢复良好(但无法从我的本地页面访问)-我不确定是需要隔离<template>
还是缺少同样简单的东西。
如果有关导入的链接文章消失:一旦获取了导入的内容,就必须从<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)来挖掘并查找导入内容。
无法从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导入,因为它们已经被弃用,并且可能会从规范中删除。请考虑使用AJAX请求获取HTML。你可以在这里找到一个例子。