Search code examples
javascripthtmlpolymerweb-componentcustom-element

Is it possible to create a web component anyone can use without installation?


I'm just getting started with web components, and if I understand correctly, the point is for them to be reusable by anyone. Is it possible to create a component that can be used by anyone simply by adding a piece of html to their static site (similar to how JavaScript widgets are added, simply by copy-pasting a few lines of code), or does it need to be installed by someone? Or is this not an intended use case of web components?


Solution

  • Yes. A Web Component is a kind of "Javascript widget".

    Typicially, you define a Web Component in a Javascript file. You can then include it in any HTML with a <script> element.

    Example with a minimal custom element called <hello-world>:

    In hello-world.js:

    customElements.define( 'hello-world', class extends HTMLElement {
        constructor() {
            super()
            this.attachShadow( {mode: 'open' })
                .innerHTML = 'Hello World!'
        }
    } )
    

    In your main page index.html:

    <html>
        <head>
            <!-- import the web component -->
            <script src="hello-world.js">
        </head>
        <body>
            <!-- use the new element -->
            <hello-world></hello-world>
        </body>
    </html>
    

    Note: alternately, one could also copy-paste the Javascript code that defines the custom element to its main HTML page.