【问题标题】:HTMl Import own WebComponentHTML 导入自己的 WebComponent
【发布时间】:2014-07-16 14:31:47
【问题描述】:

在我的 index.html 中,我导入了一个带有模板、Shadow DOM 等的外部 HTML 文件。一个自定义 Web 组件。

// index.html

... 
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.4/platform.js"></script>
<link rel="import" href="/html-components/userlogin-header.html" >
<head>
<body>
<userlogin-header username="Test User"userimage="http://domain.com/img.jpg"></userlogin-header>
...

还有另外一个文件userlogin-header.html:

// userlogin-header.html

<template id="userlogin-header">

    <div class="imgbox">
        <img src="" class="userimage">
    </div>
    <div class="userinfo">                          
        <div class="name"><span class="username"></div>                     
    </div>
</template>


<script>
    var doc = this.document.currentScript.ownerDocument,
    UserLoginProto = Object.create( HTMLElement.prototype );
    UserLoginProto.createdCallback = function() {
        var template = doc.querySelector( "#userlogin-header" ),
        box = template.content.cloneNode( true );

        this.shadow = this.createShadowRoot();
        this.shadow.appendChild( box );

        var username = this.shadow.querySelector( '.userinfo .username' );
        username.innerHTML = ( this.getAttribute( 'username' ) || 'Unbekannt' );

        var imageurl = this.shadow.querySelector( 'img.userimage' );

        imageurl.src = 'https://secure.gravatar.com/avatar/' + this.getAttribute( 'userimage' ) + '1?s=40&d=http://s3-01.webmart.de/web/support_user.png';
    };

     var Xuserlogin = doc.registerElement( 'userlogin-header', { 'prototype' : UserLoginProto } );
</script>

问题是调用index.html出现如下错误

Uncaught TypeError: Cannot read property 'content' of null 

如果我在 Chrome 中启用 HTML 导入,一切正常。但是后来我禁用了这个并使用 platform.js 代替了这个错误。

这个问题有什么解决办法吗?我不想使用整个聚合物框架。

【问题讨论】:

  • platform.js 是您的&lt;head&gt; 中第一个包含的文件吗?
  • 是的,这是直接在之后的第一个包含

标签: javascript html import platform web-component


【解决方案1】:

这是 polyfill 的 this caveat 的症状。

在原生 HTML 导入中,document.currentScript.ownerDocument 引用导入文档本身。在 polyfill 中使用 document._currentScript.ownerDocument(注意下划线)。

一旦你改变了它,你还需要使用 document.registerElement 而不是 doc.registerElement。您想注册元素,使其对 importing 文档可见,而不是导入的文档。

var Xuserlogin = document.registerElement(...);

这是working plunk

【讨论】:

  • 我自己也遇到了这个问题。谢谢!
猜你喜欢
  • 2020-08-29
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
相关资源
最近更新 更多