7

I'm trying to build a simple web component without any external dependencies. Just two html files, one index.html and one webcomponent.html.

I have some personal html projects where I'd like to separate out the global html namespace into smaller files. I do not want ot use any external library like polymer for this. Neither I want to use any build system or webserver.

All the examples I found online either need an external build system or a library. Also they don't tend to work without a webserver. For instance, webcomponents/hello-world claims to use vanilla-js. But in fact, it does not as it depends on Bower.

Just two html files which work in my local edit-save-refresh development cycle. Is this actually possible? If so, how? If not, what's the closest compromise possible?

Supersharp
  • 29,002
  • 9
  • 92
  • 134
Ruudjah
  • 807
  • 7
  • 27
  • 2
    [Bower](https://bower.io/) is a package manager. The component itself doesn't depend on Bower, but rather its build system that does. The project uses Bower to download the `webcomponents` polyfill. You'll notice that the component's [source](https://github.com/webcomponents/hello-world-element/blob/master/hello-world.html) contains only vanilla JS. – tony19 Dec 05 '16 at 18:15
  • 2
    If you provide an example including Bower, the example is dependent on Bower. It doesn't matter if Bower is used for code or just a build. So the *component* indeed does not depend on Bower, but the *example* does. – Ruudjah Dec 08 '16 at 14:43

2 Answers2

8

Here is a minimal Custom Element example with 2 files:

1. Create your custom elemnt in a separate file, for example hello-world.js:

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

2. Import and use your custom element in the main, index.html file:

<html>
<head>
    <script src='hello-world.js'></script>
<body>
    <hello-world></hello-world>
Supersharp
  • 29,002
  • 9
  • 92
  • 134
  • 2
    HTML import is not supported anymore, and may never be :https://stackoverflow.com/questions/34408880/is-html-import-still-supported-in-google-chrome – pdem Feb 19 '20 at 10:24
  • 1
    @pdem You're right. Now we should package the Custom Element definition in a Javascript file instead. I will update the answer soon – Supersharp Feb 19 '20 at 11:29
2

Code:

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>
dasfdsa
  • 7,102
  • 8
  • 51
  • 93