我有以下本地 html:
<html>
<head>
<link rel="import" href="https://mygithub.github.io/webcomponent/">
</head>
<body>
<!-- This is the custom html component I attempted to create -->
<img-slider></img-slider>
</body>
</html>
以及对模板的以下尝试:
<template>
<style>
.redColor{
background-color:red;
}
</style>
<div class = "redColor">The sky is blue</div>
</template>
<script>
// Grab our template full of slider markup and styles
var tmpl = document.querySelector('template');
// Create a prototype for a new element that extends HTMLElement
var ImgSliderProto = Object.create(HTMLElement.prototype);
// Setup our Shadow DOM and clone the template
ImgSliderProto.createdCallback = function() {
var root = this.createShadowRoot();
root.appendChild(document.importNode(tmpl.content, true));
};
// Register our new element
var ImgSlider = document.registerElement('img-slider', {
prototype: ImgSliderProto
});
</script>
如中所述本文。当我运行代码时,我得到:
未捕获的类型错误:无法读取 null 的属性“内容”
在 HTMLElement.ImgSliderProto.createdCallback ((index):20)
换句话说document.querySelector('template');
返回空值。是什么赋予了?
我的目标是创建自定义 html 元素并将其显示在链接模板代码的网站上。我 100% 确定我正确地提取了远程模板代码(显然,因为我在该代码中收到了错误)。
附:我使用的是最新的 Chrome,所以我不需要 polyfill。
尝试这个:
var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');
您遇到的问题是模板并不是真正的一部分document
但它是一部分currentScript
。由于填充和浏览器的差异,您需要检查currentScript
and _currentScript
才能正常工作。
另请注意,HTML 导入永远不会完全跨浏览器。大多数 Web 组件正在转向基于 JavaScript 的代码,并将使用 ES6 模块加载进行加载。
有些东西可以帮助在 JS 文件中创建模板。使用反引号 (`) 是一种合理的方法:
var tmpl = document.createElement('template');
tmpl.innerHTML = `<style>
.redColor{
background-color:red;
}
</style>
<div class = "redColor">The sky is blue</div>`;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)