创建和使用自定义HTML组件?

时间:2017-11-21 17:51:40

标签: 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-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>

this article所述。当我运行代码时,我得到:

  

未捕获的TypeError:无法读取属性&#39;内容&#39;为null       at HTMLElement.ImgSliderProto.createdCallback((index):20)

换句话说,document.querySelector('template');返回null。是什么给了什么?

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

P.S。我使用的是最新的Chrome,因此我不需要使用polyfill。

1 个答案:

答案 0 :(得分:4)

试试这个:

  var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');

您遇到的问题是该模板并非真正属于document,但它是currentScript的一部分。由于填充和浏览器差异,您需要检查currentScript_currentScript是否正常工作。

另请注意,HTML Imports永远不会完全跨浏览器。大多数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>`;
相关问题