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

VSO*_*VSO 1 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

以及对模板的以下尝试:

<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>
Run Code Online (Sandbox Code Playgroud)

本文所述。当我运行代码时,我得到:

未捕获的类型错误:无法在 HTMLElement.ImgSliderProto.createdCallback ((index):20) 处读取 null 的属性“内容”

换句话说,document.querySelector('template');返回空值。是什么赋予了?

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

PS 我使用的是最新的 Chrome,所以我不需要 polyfill。

Int*_*lia 5

尝试这个:

  var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');
Run Code Online (Sandbox Code Playgroud)

您遇到的问题是模板并不是真正的一部分,document但它是currentScript. 由于 polyfills 和浏览器的差异,您需要检查currentScript_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>`;
Run Code Online (Sandbox Code Playgroud)