Search code examples
javascriptweb-componentshadow-dompolyfillshtml-imports

Webcomponents Polyfill not working


I am trying to polyfill webcomponents as explained at https://www.webcomponents.org/polyfills/ since I wanted my sample app to work on both Chrome and Firefox. However I am getting ReferenceError: customElements is not defined error in Firefox. See my code below on the index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="robots" content="index, follow">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Sample</title>
    <link rel="stylesheet" href="css/site.css">
    <!-- Components -->
    <link rel="import" href="components/global/site-navigation.html">
</head>

<body>
    <script>
        (function () {
            if ('registerElement' in document
                && 'import' in document.createElement('link')
                && 'content' in document.createElement('template')) {
                // platform is good!
            } else {
                // polyfill the platform!
                var e = document.createElement('script');
                e.src = 'js/webcomponents.js';
                document.body.appendChild(e);
            }
        })();
    </script>
    <site-navigation></site-navigation>
</body>    
</html>

What am I missing?

PS: Everything works fine in Chrome (with/without the polyfill)


Solution

  • You are using an old version of webcomponentsjs polyfill, which implements Custom Elements v0's document.registerElement() instead of v1's customElements.define().

    You should use the new version 1.0 on github.

    Just load the webomponents-lite.js script in the <head> part of your page:

    <script src="webcomponents-lite.js"></script>
    

    Update: Now polyfill version 2 was released. HTML Imports polyfill is not shipped any more, but can be used it separately, or you can still download v1 branch.