Importing Polymer web components from remote URLs

2019-08-21 08:21发布

问题:

I have created a custom Polymer 2.0 based web component which aims to be installed on third-party websites in order to display content managed from my website.

The web component in question depends on 3 other custom web components but also on iron-ajax, iron-dropdown, iron-icon, iron-icon-svg, marked-element and paper-icon-button.

In order to maximize browsers compatibility, the code is transpiled to ES5 by using polymer-build with the default es5-bundled preset.

Once done, the build folder is deployed on Firebase hosting and I get an URL for including required files on third-party websites:

<script>if (!window.customElements) {
        document.write('<!--');
    }</script>
    <script type="text/javascript" src="https://cdn.mydomain.com/libs/webcomponentsjs/custom-elements-es5-adapter.js"></script>
    <!--! do not remove -->
    <script src="https://cdn.mydomain.com/libs/webcomponentsjs/webcomponents-loader.js"></script>
    <link rel="import" href="https://cdn.mydomain.com/components/my-component.html">

When I add the previous piece of code in a blank page, I can create a new instance of my-component without any problem and all is working as expected.

However, when I include the code above in a web page that already uses Polymer, then I get a lot of errors similar to the following:

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry

This is understandable since the import above embeds Polymer but Polymer is already loaded on the page.

I was thinking to exclude Polymer and dependencies such as iron-ajax, etc. from my custom web component definition. This way, I could directly use the web component on a page that already embeds Polymer whereas pages that don't have Polymer import Polymer and required dependencies.

Unfortunately, when I have tried, I was not able to generate babel helpers which are usually automatically created by polymer-build. Furthermore, even if I succeed to get babel helpers, then this solution will not always work since all dependent code must be transpiled to ES5. This means that third-party webpages that use an ES6 version of Polymer can still not use my custom web component...

The only solution I can though about at this time is to release my custom web component in a private repository and distribute the source to developers that need to include my custom web component in a third party webpage that already embeds Polymer. This way, they can locally import the component definition and include it to their build. Unfortunately, the solution has the major drawback to prevent transparent updates from my side. I need to notify developers about changes or they need to poll for changes :(

Do you have already encountered such a situation with Polymer? what are you advices?