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

Create and Use a Custom HTML 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所述。当我 运行 代码时,我得到:

Uncaught TypeError: Cannot read property 'content' of null at HTMLElement.ImgSliderProto.createdCallback ((index):20)

换句话说document.querySelector('template'); returns null。给出了什么?

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

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

试试这个:

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

您 运行 遇到的问题是模板实际上并不是 document 的一部分,而是 currentScript 的一部分。由于 polyfill 和浏览器的差异,您需要检查 currentScript_currentScript 才能正常工作。

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

有些东西可以帮助在 JS 文件中创建模板。使用反引号 (`) 是一种合理的方式:

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