【问题标题】:polymer not displaying html from import聚合物不显示导入的 html
【发布时间】:2014-10-12 00:14:49
【问题描述】:

我刚刚开始使用聚合物构建 Web 组件,并且正在按照教程进行操作。

我刚刚开始,我正在通过脚本将我的组件添加到我的页面,但我的模板中的 html 没有显示出来。

这是我到目前为止所得到的。

document.addEventListener("DOMContentLoaded", function() {
    if(!window.Polymer){
        var poly = document.createElement('script');
        poly.src = "http://cdnjs.cloudflare.com/ajax/libs/polymer/0.3.4/platform.js";
        document.head.appendChild(poly);   
    }

    var template = document.createElement('link');
    template.setAttribute("rel", "import");
    template.setAttribute("href", "http://localhost:8081/first-widget.html");


    document.body.appendChild(template);


    var widget = document.createElement('my-widget');
    document.body.appendChild(widget);

    setTimeout(function(){
        Polymer('my-widget');
    },1000);
 });

我的小部件是

<polymer-element name="my-widget">
    <template>
        <h1>This is from the Polymer</h1>
    </template>
</polymer-element>

我的理解是,这应该在我的my-widget 标记中显示模板中我的html 内容。我有 localhost:8081 通过 CORS 提供模板的内容,所以这不是问题,我可以通过元素检查器看到模板加载到 chrome 中。所以我不确定为什么我没有收到我的内容。

有没有一种方法可以引导聚合物?

【问题讨论】:

    标签: polymer web-component


    【解决方案1】:

    在您的小部件中,您需要导入 polymer.html 并使用 noscript 属性:

    <link rel="import" href="path/to/polymer.html">
    
    <polymer-element name="my-widget" noscript>
        <template>
            <h1>This is from the Polymer</h1>
        </template>
    </polymer-element>
    

    或注册您的元素:

    <link rel="import" href="path/to/polymer.html">
    
    <polymer-element name="my-widget">
        <template>
            <h1>This is from the Polymer</h1>
        </template>
        <script>
            Polymer({});
        </script>
    </polymer-element>
    

    更多关于创建元素的信息:http://www.polymer-project.org/docs/start/creatingelements.html

    【讨论】:

    • 我一直在尝试添加polymer.html,但据我所知,它只包含一个导入polymer.js 脚本的链接,我已经将它包含在我的页。如果我包含了 polymer.html,我会收到关于在 html 上使用 appendChild 的错误,这显然是两次加载聚合物的结果。 groups.google.com/a/dartlang.org/forum/#!msg/web/bgMajiu_iR4/…。我也尝试过使用 polymer.html,并没有在我的脚本中加载库,但我仍然没有填充元素。
    【解决方案2】:

    您需要将 html 运行到服务器中。 我正在使用http-server,这很简单。

    npm 安装 http-server

    基本上你导航到 index.html 文件并运行“http-server”。

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      原来我包含了 platform.js 而不是 polymer.js 如果有人像我一样动态加载聚合物(因为我们正在构建一个其他人可以在他们的页面中包含的小部件),似乎最好使用@pikanezi 描述的noscript 属性,因为你不运行以这种方式进入时间问题。

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        相关资源
        最近更新 更多