javascript - Webcomponents Polyfill 不工作

标签 javascript web-component shadow-dom polyfills html-imports

我正在尝试按照 https://www.webcomponents.org/polyfills/ 中的说明填充 Web 组件因为我希望我的示例应用程序可以在 Chrome 和 Firefox 上运行。但是我在 Firefox 中收到 ReferenceError: customElements is not defined 错误。在 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>

我错过了什么?

PS:在 Chrome 中一切正常(有/没有 polyfill)

最佳答案

您正在使用旧版本的 webcomponentsjs polyfill,它实现了自定义元素 v0 的 document.registerElement()而不是 v1 的 customElements.define() .

您应该使用新的 version 1.0 on github .

只需在 <head> 中加载 webomponents-lite.js 脚本页面的一部分:

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

更新:现已发布 polyfill 版本 2。 HTML Imports polyfill 不再提供,但可以单独使用,或者您仍然可以下载 v1 branch

关于javascript - Webcomponents Polyfill 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47183862/

相关文章:

javascript - 在自定义元素中获取元素引用

javascript - 获取影子根宿主元素

css - 将 SCSS `@extends` 与深层元素样式一起使用

iframe - 在 Selenium WebDriver 中访问 iFrame 文档内的元素

javascript - 如果用户关闭选项卡,Vuejs 则发布请求

javascript - 如果存在 prop,如何将 CSS 应用于 body 元素?

javascript - 我可以用 JavaScript 编写 iOS (Cocoa) 应用程序吗?

html - Polymer 1.1 中的共享样式和外部样式表

javascript - VueJs - 两个数字之间循环的最佳实践