Search code examples
polymerweb-componentcustom-elementpolymer-elements

Usage of Polymer 3.0 custom element from another webapp


I'm trying to consume a custom web component built with Polymer CLI in my webapp. I went though the following steps in order to setup a first dummy custom element with polymer:

using node v8.9.1, npm v5.5.1, polymer-cli v1.7.2

  1. mkdir my-custom-element && cd my-custom-element
  2. polymer init polymer-3-element
  3. polymer serve

The demo app under http://localhost:8000/demo/ generated by polymer serve imports my custom element and is cross-browser compatible. Specifically it loads the custom element in IE 11 - which is a requirement in my project.

My question is: How can I bootstrap my webapp index.html to use my custom element (that may be hosted on another server) just like in the demo app. I didn't yet find documentation on this.

For Polymer Elements e.g. there is documentation under https://elements.polymer-project.org/guides/using-elements#using-elements on how to bootstrap. Unfortunately this does not work with Polymer 3.0 elements (e.g. b/c of module imports vs. html imports).


Solution

  • I think the best way to go is the following excerpt from the polymer init generated demo/index.html:

    <!doctype html>
    <html lang="en">
     <head>
       <meta charset="utf-8">
       <script type="text/javascript" src="assets/webcomponents-loader.js">/script>
       <script type="module" src="http://localhost:8000/custom-polymer-element.js"></script>
     </head>
     <body>
       <custom-polymer-element></custom-polymer-element>
     </body>
    </html>
    

    The webcomponents-loader.js from https://github.com/webcomponents/webcomponentsjs / npm package:

    "@webcomponents/webcomponentsjs": "^2.0.0",
    

    is also used by polymer serve and will bootstrap the custom element.

    However, this currently is not sufficient because of issues with cross browser compatibility. I had to write additional bootstrapping code to get it to work in Chrome 65+, FF 59+ and IE 11 which you can find here: https://github.com/robertfoobar/es6-custom-element