Javascript 创建并使用自定义HTML组件?

Javascript 创建并使用自定义HTML组件?,javascript,html,css,templates,web-component,Javascript,Html,Css,Templates,Web Component,我有以下本地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-slide

我有以下本地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>
如中所述。当我运行代码时,我得到:

未捕获的TypeError:无法读取null的属性“content” 在HTMLElement.ImgSliderProto.createdCallback索引处:20

换句话说,document.querySelector'template';返回null。有什么好处

我的目标是创建自定义html元素,并将其显示在链接模板代码的网站上。显然,我100%确信我正确地提取了远程模板代码,因为我在该代码中得到了错误

另外,我使用的是最新的Chrome,所以我不需要polyfills

试试这个:

  var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');
您遇到的问题是,模板实际上不是文档的一部分,但它是currentScript的一部分。由于多边形填充和浏览器的差异,您需要检查currentScript和_currentScript是否正常工作

还要注意,HTML导入永远不会完全跨浏览器。大多数web组件正在转向基于JavaScript的代码,并将使用ES6模块加载进行加载

有一些东西可以帮助在JS文件中创建模板。使用backtick`是一种合理的方法:

var tmpl = document.createElement('template');
tmpl.innerHTML = `<style>
  .redColor{
    background-color:red;
  }
</style>
<div class = "redColor">The sky is blue</div>`;
试试这个:

  var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');
您遇到的问题是,模板实际上不是文档的一部分,但它是currentScript的一部分。由于多边形填充和浏览器的差异,您需要检查currentScript和_currentScript是否正常工作

还要注意,HTML导入永远不会完全跨浏览器。大多数web组件正在转向基于JavaScript的代码,并将使用ES6模块加载进行加载

有一些东西可以帮助在JS文件中创建模板。使用backtick`是一种合理的方法:

var tmpl = document.createElement('template');
tmpl.innerHTML = `<style>
  .redColor{
    background-color:red;
  }
</style>
<div class = "redColor">The sky is blue</div>`;

谢谢,现在尝试,你能解释多一点吗?我的更改回答了你的问题吗?这解决了我的问题,一旦接受时间缓冲区用完,我会回来接受。谢谢。谢谢,现在尝试,你能解释多一点吗?我的更改回答了你的问题吗?这解决了我的问题,一旦验收时间缓冲区用完,我会回来验收。谢谢。可能的副本可能的副本