使用网络组件的香草你好世界应用程序

时间:2016-12-05 17:05:46

标签: javascript html5 web-component custom-element

我正在尝试构建一个没有任何外部依赖关系的简单Web组件。只有两个html文件,一个index.html和一个webcomponent.html。

我有一些个人html项目,我想将全局html命名空间分成较小的文件。我不想为此使用像聚合物这样的任何外部库。我都不想使用任何构建系统或网络服务器。

我在网上找到的所有例子都需要外部构建系统或库。如果没有网络服务器,他们也不会工作。例如,webcomponents/hello-world声称使用vanilla-js。但事实上,它并不依赖于鲍尔。

只有两个html文件在我的本地编辑 - 保存 - 刷新开发周期中工作。这有可能吗?如果是这样,怎么样?如果没有,最接近的妥协可能是什么?

2 个答案:

答案 0 :(得分:4)

这是一个包含2个文件的最小自定义元素示例:

1。在单独的文件中创建自定义元素,例如 hello-world.html

Traversable

2. index.html 文件中导入并使用自定义元素:

<script>
class HelloWorld extends HTMLElement {
    connectedCallback () {
        this.innerHTML = 'hello, world!'
    }
}
customElements.define( 'hello-world', HelloWorld )
</script>

答案 1 :(得分:0)

代码:

class HelloWorld extends HTMLElement {
    constructor() {
      super();
      // Attach a shadow root to the element.
      let shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.innerHTML = `<p>hello world</p>`;
    }
  }
  customElements.define('hello-world', HelloWorld);
  <hello-world></hello-world>

相关问题