Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMl Import own WebComponent

In my index.html I import an external HTML file with an Template, Shadow DOM etc. A custom web Component.

// 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>
...

And the other file 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>

The problem is that there is the following error on call index.html

Uncaught TypeError: Cannot read property 'content' of null 

If I enable HTML Import in my Chrome everything works correctly. But then I disable this and use platform.js instead there is this error.

Is there any solution for this problem? I do not want to use the whole polymer framework.

like image 893
Christopher Avatar asked Mar 08 '26 09:03

Christopher


1 Answers

This is a symptom of this caveat of the polyfill.

In a native HTML Imports, document.currentScript.ownerDocument references the import document itself. In the polyfill use document._currentScript.ownerDocument (note the underscore).

Once you change that, you also need to use document.registerElement instead of doc.registerElement. You want to register the element such that it's visible to the importing document, not the imported one.

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

Here's a working plunk.

like image 54
CletusW Avatar answered Mar 11 '26 05:03

CletusW